我用
PHP编写了一个下载脚本,一直工作到昨天.今天我试着下载其中一个文件,发现它突然停止了工作:
PHP Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 119767041 bytes) in E:\home\tecnoponta\web\aluno\download.PHP on line 52
出于某种原因,PHP试图在内存中分配文件的大小,我不知道为什么.如果文件大小小于内存限制,我可以毫无问题地下载它,问题在于更大的文件.
我知道可以通过增加PHP.ini中的内存限制甚至在代码上使用ini_set来纠正它,但我想要一个更准确的方法来解决这个问题以及为什么它停止工作的答案.
这是我的代码:
$file = utf8_decode($_GET['d']);
header('Content-Description: File Transfer');
header('Content-disposition: attachment; filename='.$file);
header('Content-Type: application/octet-stream');
header('Content-transfer-encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$file = "uploads/$curso/$file";
ob_clean();
flush();
readfile($file);
echo "<script>window.history.back();</script>";
exit;
从
php.net for readfile开始:
readfile() will not present any memory issues,even when sending large
files,on its own. If you encounter an out of memory error ensure that
output buffering is off with ob_get_level().
从php.net for ob_clean开始:
This function does not destroy the output buffer like ob_end_clean()
does.
你需要的是这个:
if (ob_get_level()) {
ob_end_clean();
}
还要考虑添加:
header('Content-Length: ' . filesize($file));