加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用readfile时“允许内存…耗尽”

发布时间:2020-12-13 13:47:42 所属栏目:PHP教程 来源:网络整理
导读:我用 PHP编写了一个下载脚本,一直工作到昨天.今天我试着下载其中一个文件,发现它突然停止了工作: PHP Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 119767041 bytes) in E:hometecnopontawebalunodownload.php o
我用 PHP编写了一个下载脚本,一直工作到昨天.今天我试着下载其中一个文件,发现它突然停止了工作:

PHP Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 119767041 bytes) in E:hometecnopontawebalunodownload.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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读