PHP - 读取FTP文件而不下载/在本地保存

时间:2014-06-04 00:32:14

标签: php file ftp

我想获取FTP文件内容而不在本地保存。

这是我到目前为止所做的:

$ftp_server = "my_server";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to the server");

if (@ftp_login($ftp_conn, "username", "password")) {

    $local_file = 'C:\Users\user\Desktop\testing.txt';
    $fp = fopen($local_file, "w");

    $d = ftp_nb_fget($ftp_conn, $fp, "commands.yml", FTP_BINARY);

    while ($d == FTP_MOREDATA) {
        $d = ftp_nb_continue($ftp_conn);
    }

    if ($d != FTP_FINISHED) {
        echo "Error downloading $server_file";
        exit(1);
    }

    ftp_close($ftp_conn);
    fclose($fp);

    $filename = 'C:\Users\user\Desktop\testing.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);

    echo $contents;

} else {
    echo "Couldn't establish a connection.";
}

上面的代码保存文件并读取文件内容。是否可以在不将其保存在本地的情况下读取文件?

1 个答案:

答案 0 :(得分:2)

来自bob at notallhere dot com的{​​{3}}:

  

不想使用中间文件?使用'php:// output'作为   filename然后使用输出缓冲捕获输出。

ob_start();
$result = ftp_get($ftp, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();