【问题标题】:Getting "FTP server reports 550 Could not get file size." when using FTP URL in fopen获取“FTP 服务器报告 550 无法获取文件大小。”在 fopen 中使用 FTP URL 时
【发布时间】:2017-04-19 20:19:46
【问题描述】:

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

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

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

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

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

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

我确定文件存在

【问题讨论】:

    标签: php ftp


    【解决方案1】:

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

    请改用ftp_fget

    $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: How do I read a .txt file from FTP server into a variable?

    【讨论】:

      【解决方案2】:

      根据@Martin Prikryl 的回答,这里有一个修改后的,可以使用任何网址格式。

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多