【问题标题】:Read contents of every file in FTP directory using one connection使用一个连接读取 FTP 目录中每个文件的内容
【发布时间】:2015-03-22 21:39:18
【问题描述】:

我的目标是连接到一个 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?

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

【问题讨论】:

    标签: php ftp


    【解决方案1】:

    为避免必须为每个文件连接/登录,请使用 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);
    }
    

    (你应该添加一些错误检查。)

    【讨论】:

    • 好的 - 谢谢。因此,如果我想保留我不会使用的文件:取消链接?
    • 当然,但在这种情况下,您可能希望使用更有意义的文件和路径,例如$temp_path = "/path/".$file$temp_path 变量名也会令人困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2017-09-26
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多