2011-06-08 22 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');