加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用一个连接读取FTP目录中每个文件的内容

发布时间:2020-12-13 22:54:54 所属栏目:PHP教程 来源:网络整理
导读:我的目标是连接到FTP帐户,读取特定文件夹中的文件,抓取内容并列出到我的屏幕. 这就是我所拥有的: // set up basic connection$conn_id = ftp_connect('HOST_ADDRESS');// login with username and password$login_result = ftp_login($conn_id,'USERNAME','
我的目标是连接到FTP帐户,读取特定文件夹中的文件,抓取内容并列出到我的屏幕.

这就是我所拥有的:

// set up basic connection
$conn_id = ftp_connect('HOST_ADDRESS');

// login with username and password
$login_result = ftp_login($conn_id,'USERNAME','PASSWORD');

if (!$login_result)
{
    exit();
}

// get contents of the current directory
$contents = ftp_nlist($conn_id,"DirectoryName");

$files = [];

foreach ($contents AS $content)
{
    $ignoreArray = ['.','..'];
    if ( ! in_array( $content,$ignoreArray) )
    {
        $files[] = $content;
    }
}

上面的工作很好,以获取我需要从中获取内容的文件名.接下来,我想通过文件名数组进行递归,并将内容存储到变量中以便进一步处理.

我不知道如何做到这一点,我想它会需要像这样:

foreach ($files AS $file )
{
    $handle = fopen($filename,"r");
    $contents = fread($conn_id,filesize($file));
    $content[$file] = $contents;
}

上面的想法来自这里:
PHP: How do I read a .txt file from FTP server into a variable?

虽然我不喜欢每次都要连接以获取文件内容的想法,但是我更喜欢在初始实例上进行连接.

解决方法

为避免必须为每个文件连接/登录,请使用 ftp_get并重用您的连接ID($conn_id):

foreach ($files as $file)
{
    // Full path to a remote file
    $remote_path = "DirectoryName/$file";
    // Path to a temporary local copy of the remote file
    $temp_path = tempnam(sys_get_temp_dir(),"ftp");
    // Temporarily download the file
    ftp_get($conn_id,$temp_path,$remote_path,FTP_BINARY);
    // Read the contents of temporary copy
    $contents = file_get_contents($temp_path);
    $content[$file] = $contents;
    // Discard the temporary copy
    unlink($temp_path);
}

(您应该添加一些错误检查.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读