gpt4 book ai didi

php - 使用 readfile 时为 "Allowed memory .. exhausted"

转载 作者:可可西里 更新时间:2023-10-31 23:54:45 25 4
gpt4 key购买 nike

我用 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));

关于php - 使用 readfile 时为 "Allowed memory .. exhausted",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com