我想将远程ftp服务器上的文件读取到变量。我试着用地址阅读
fopen("ftp://user:pass@localhost/filetoread");
和
$contents = file_get_contents('ftp://ftpuser:123456789@localhost/file.conf');
echo $contents;
两者都不起作用。我还尝试将GET
请求直接发送到也不起作用的网址。如何在不下载的情况下阅读FTP文件?
我检查了php警告:
PHP警告:file_get_contents(ftp://...@localhost/file.conf):无法打开流:FTP服务器报告550无法获取文件大小。
在第2行的/var/www/html/api/listfolder.php
我确定该文件存在
答案 0 :(得分:1)
PHP FTP URL wrapper似乎需要FTP GRANT SUPER ON db_name.* TO user@localhost IDENTIFIED BY 'password';
命令,这是FTP服务器不支持的。
改为使用ftp_fget
:
SIZE
(添加错误处理)
请参阅PHP: How do I read a .txt file from FTP server into a variable?
答案 1 :(得分:0)
基于@Martin Prikryl 的回答,这里有一个修订版,适用于任何 url 格式。
function getFtpUrlBinaryContents($url){
$path_info = parse_url($url);
$conn_id = ftp_connect($path_info['host'], $path_info['port'] ?? 21);
if(isset($path_info['user'])){
ftp_login($conn_id, $path_info['user'], $path_info['pass'] ?? '');
}
ftp_pasv($conn_id, true);
$h = fopen('php://temp', 'r+');
ftp_fget($conn_id, $h, $path_info['path'], FTP_BINARY, 0);
$fstats = fstat($h);
fseek($h, 0);
$contents = fread($h, $fstats['size']);
fclose($h);
ftp_close($conn_id);
return $contents;
}
$contents = getFtpUrlBinaryContents('ftp://ftpuser:123456789@localhost/file.conf');
echo $contents;