“允许的内存..用尽"使用readfile时 [英] "Allowed memory .. exhausted" when using readfile

查看:79
本文介绍了“允许的内存..用尽"使用readfile时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用PHP编写了一个下载脚本,该脚本一直运行到昨天.今天,我试图下载其中一个文件,只是发现它突然停止工作:

I made a download script in PHP that was working until yesterday. Today I tried to download one of the files only to discover that suddenly it stopped working:

PHP致命错误:在第52行的E:\ home \ tecnoponta \ web \ aluno \ download.php中,耗尽了67108864字节的内存(尝试分配119767041字节)

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试图在内存中分配文件的大小,我不知道为什么.如果文件大小小于内存限制,那么我可以下载它而没有问题,问题出在更大的文件上.

For some reason PHP is trying to allocate the size of the file in the memory, and I have no idea why. If the file size is smaller than the memory limit, I can download it without a problem, the problem is with bigger files.

我确实知道可以通过增加php.ini中的内存限制甚至在代码上使用ini_set来纠正它,但是我想找到一种更准确的方法来解决此问题,并给出为什么它停止工作的答案.

I do know that it can be corrected by increasing the memory limit in php.ini or even use ini_set on the code but I would like a more accurate way to fix this and an answer to why it stopped working.

这是我的代码:

$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读取文件:

readfile()不会出现任何内存问题,即使在发送大文件时也是如此 文件.如果遇到内存不足错误,请确保 使用ob_get_level()关闭输出缓冲.

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().

用于ob_clean的php.net :

此函数不会破坏ob_end_clean()之类的输出缓冲区 会.

This function does not destroy the output buffer like ob_end_clean() does.

您需要的是这个

if (ob_get_level()) {
      ob_end_clean();
    }

还可以考虑添加以下内容:

Also consider adding this:

header('Content-Length: ' . filesize($file));

这篇关于“允许的内存..用尽"使用readfile时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆