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?
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.
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