2011-06-08 90 views
1

我尝试在php中渲染zip文件。 代码:php渲染大型zip文件 - 达到内存限制

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

下载的文件,只有几个字节。这是一个错误消息:

<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 />

我不希望增加memory_limit的php.ini中。什么是替代方法来正确渲染大型zip文件而不用修改全局设置?

+0

哪里zip文件来自何处?从磁盘还是你在飞行中创建它?基本的解决方案是流式传输数据,因此您不需要同时将其保存在内存中。 – Eelke 2011-06-08 17:42:44

+0

你用什么函数来转储文件?你有没有看过'readfile()'? http://php.net/readfile – Dereleased 2011-06-08 17:43:37

+0

从磁盘读取它 – tanon 2011-06-08 18:01:45

回答

4

流下载,所以它不会在内存中窒息。 微小例如:

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

添加正确的输出头的下载,你应该解决的问题。

0

PHP实际上提供了一种简单的方法,以输出一个二进制文件直接到Apache而不首先在存储器积攒它经由readfile()功能:

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