php rendering large zip file - memory limit reached

佐手、 提交于 2019-11-28 06:25:15

问题


I try to render a zip file in php. Code:

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');

The downloaded file, is only few bytes. It is an error message:

<br /> <b>Fatal error</b>: Allowed memory size of 16777216 bytes exhausted (tried to allocate 41908867 bytes) in <b>/var/www/common_index/main.php</b> on line <b>217</b><br />

I do not wish to increase memory_limit in php.ini. What are alternative ways to properly render large zip files without tinkering with global settings?


回答1:


Stream the download, so it doesn't choke on memory. Tiny example:

$handle = fopen("exampe.zip", "rb");
while (!feof($handle)) {
    echo fread($handle, 1024);
    flush();
}
fclose($handle);

Add correct output headers for downloading, and you should solve the problem.




回答2:


PHP actually provides an easy method to output a binary file directly to Apache without stashing it in memory first via the readfile() function:

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile('file.zip');


来源:https://stackoverflow.com/questions/6282887/php-rendering-large-zip-file-memory-limit-reached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!