我使用以下代码从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; }
如何使它直接将文件发送给用户(浏览器)而不保存到磁盘,也无需重定向到ftp服务器?
只需删除输出缓冲(ob_start()和其他)。
ob_start()
仅使用此:
ftp_get($conn_id, "php://output", $file, FTP_BINARY);
虽然如果要添加Content-Length标题,则必须先使用来查询文件大小ftp_size:
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);
(添加错误处理)