我需要向客户提供像 file.zip
( ~2 GB ) 这样的大文件,每个客户都有一个。 然后我将( 使用 .htaccess
) 重定向到客户下载链接 example.com/download/f6zDaq/file.zip
像这样
example.com/download.php?id=f6zDaq&file=file.zip
但由于文件很大,我不希望PHP处理下载(而不仅仅是让Apache处理它), 这样会成为我服务器的CPU / RAM性能问题。 毕竟,要求PHP执行它涉及一个新层,因此如果没有正确完成,可能会导致这样的问题。
问:在下列解决方案中,哪一个是最佳? ( 尤其是在 cpu/ram方面)?
1: 带有
application/download
的PHP解决方案header('Content-Type: application/download'); header('Content-Disposition: attachment; filename=file.zip'); readfile("/path/to/file.zip");
1bis使用 application/octet-stream 的PHP解决方案(来自的示例 #1 这里页面)
header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=file.zip'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: '. filesize('file.zip')); readfile("/path/to/file.zip");
1ter: 带有 application/octet-stream ( 来自这里 )的PHP解决方案:
header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=file.zip'); header('Content-Transfer-Encoding: binary');//additional line header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0');//additional line header('Pragma: public'); header('Content-Length: '. filesize('file.zip')); readfile("/path/to/file.zip");
1quater: 另一个带有 application/force-download ( 来自这里 )的PHP变量:
header("Content-Disposition: attachment; filename=file.zip"); header("Content-Type: application/force-download"); header("Content-Length:". filesize($file)); header("Connection: close");
2: Apache解决方案,不涉及 PHP: 让Apache为文件提供服务,并使用. htaccess为同一文件( 有许多方法可以写) 提供不同的URL 。 在性能方面,它类似于让客户下载
example.com/file.zip
,由Apache服务器提供。3: 另一个PHP解决方案。这可能很有用:
$myfile = file_get_contents("file.zip"); echo $myfile;
但是这不会要求PHP将整个内容加载到内存中吗? (这在性能方面会很糟糕)
注:readfile doc表示:
readfile() 不会出现任何内存问题,即使在发送大文件时也不会出现。 如果遇到内存不足错误,请确保输出缓冲与 ob_get_level() 一起关闭。
但是,我想100%肯定它比纯Apache解决方案更慢/需要更多的CPU/内存。