通过 PHP 脚本将文件从 FTP 服务器下载到具有 Content-Length 标头的浏览器,而不将文件存储在 Web 服务器上

Bad*_*Mav 2 php ftp content-disposition http-content-length

我使用以下代码从 ftp 将文件下载到内存:

public static function getFtpFileContents($conn_id , $file)
{
    ob_start();
    $result = ftp_get($conn_id, "php://output", $file, FTP_BINARY);
    $data = ob_get_contents();
    ob_end_clean();
    if ($resul)
        return $data;
    return null;
}
Run Code Online (Sandbox Code Playgroud)

如何让它直接将文件发送给用户(浏览器)而不保存到磁盘,也不重定向到 ftp 服务器?

Mar*_*ryl 5

只需删除输出缓冲(ob_start()和其他缓冲)。

仅使用这个:

ftp_get($conn_id, "php://output", $file, FTP_BINARY);
Run Code Online (Sandbox Code Playgroud)

不过,如果您想添加Content-Length标头,则必须首先使用以下命令查询文件大小ftp_size

$conn_id = ftp_connect("ftp.example.com");
ftp_login($conn_id, "username", "password");
ftp_pasv($conn_id, true);

$file_path = "remote/path/file.zip";
$size = ftp_size($conn_id, $file_path);

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($file_path));
header("Content-Length: $size"); 

ftp_get($conn_id, "php://output", $file_path, FTP_BINARY);
Run Code Online (Sandbox Code Playgroud)

(添加错误处理)


有关更广泛的背景信息,请参阅:
从 FTP 列出并下载单击的文件