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