获取“FTP 服务器报告 550 无法获取文件大小."在 fopen 中使用 FTP URL 时

2022-01-09 00:00:00 ftp php

我想将远程 ftp 服务器上的文件读取到变量中.我试着用地址阅读

I want to read a file which is on a remote ftp server to a variable. I tried reading with address

fopen("ftp://user:pass@localhost/filetoread");

$contents = file_get_contents('ftp://ftpuser:123456789@localhost/file.conf');
echo $contents;

两者都不起作用.我还尝试将 GET 请求直接发送到同样不起作用的 URL.不下载如何读取 FTP 文件?

Neither does work. I also tried to send directly GET request to the URL which also doesn't work. How can I read the FTP file without downloading?

我检查了 php 警告,上面写着:

I checked the php warning which says:

PHP 警告:file_get_contents(ftp://...@localhost/file.conf):打开流失败:FTP 服务器报告 550 无法获取文件大小.
在/var/www/html/api/listfolder.php 第 2 行

PHP Warning: file_get_contents(ftp://...@localhost/file.conf): failed to open stream: FTP server reports 550 Could not get file size.
in /var/www/html/api/listfolder.php on line 2

我确定文件存在

推荐答案

PHP FTP URL wrapper 似乎需要 FTP SIZE 命令,你的 FTP 服务器不支持.

The PHP FTP URL wrapper seems to require FTP SIZE command, what your FTP server does not support.

使用 ftp_fget 改为:

Use the ftp_fget instead:

$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');
ftp_pasv($conn_id, true);

$h = fopen('php://temp', 'r+');

ftp_fget($conn_id, $h, '/path/to/file', FTP_BINARY, 0);

$fstats = fstat($h);
fseek($h, 0);
$contents = fread($h, $fstats['size']); 

fclose($h);
ftp_close($conn_id);

(添加错误处理)

请参阅PHP:如何将 .txt 文件从 FTP 服务器读取到变量中?

相关文章