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

标签 php ftp

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

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

关于php - 使用一个连接读取 FTP 目录中每个文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200168/

相关文章:

php ftp_get() 返回权限被拒绝

php - 如何从 ftp 服务器获取最新修改的 csv 文件值并将其插入到 mysql 表中

c# - 在 MVC/C# 中创建 CSV 文件并通过 FTP 上传到服务器

javascript - 从 Controller 中的导航器获取用户位置

php - 支持 FPDF 中的挪威字符

php - 模拟 HTTP 请求进行单元测试

javascript - Node.js 检查 ftp 凭据是否有效

PHP上传和下载文件

php - 无论如何要对 ID 进行排序?

php - 从选择查询中将值插入到 mysql