[英]ZIP a single big file in many calls using PHP PCL Zip
100 MB文件 - > 10個ZIP通話(每次通話10 MB壓縮) - > 1個ZIP文件
我應該發起10次調用,將一個100 MB的文件添加到Zip文件中(比如每次調用10 MB Zipping)。
問題是我們有一個具有內存和時間限制的系統(對於一個呼叫,它不會處理超過10到15MB的內存)。
因此,通過多次調用來壓縮大文件是基本的想法。
如果需要,我准備提供更多數據。
你以前試過PECL Zip嗎?
只需使用以下代碼壓縮兩個文件,沒有任何內存限制問題。 時間限制可能會重置。 我的環境:memory_limit為3MB,max_execution時間為20秒。
<?php
set_time_limit(0);
$zip = new ZipArchive();
$zip->open('./test.zip', ZipArchive::CREATE);
$zip->addFile('./testa'); // 1.3 GB
$zip->addFile('./testb'); // 700mb
$zip->close();
注意: set_time_limit()不能在php <5.4上使用save_mode = on
另一種方法可能是在后台進程中創建zip。 這可以避免可能的memory_limit問題。
這是一個例子: http : //pastebin.com/7jBaPedb
用法:
try {
$t = new zip('/bin', '/tmp/test.zip');
$t->zip();
if ($t->waitForFinish(100))
echo "Succes :)";
else
echo $t->getOutput();
} catch ($e) {
echo $e->getMessage();
}
您可以在數據庫中編寫pid並在文件完成后提供服務,而不是等到進程結束。
閱讀你的問題我首先開始創建一個分塊的拉鏈包裝機,按照你的要求做。 它會生成一個包含指向網頁的鏈接的數組,您必須按順序打開它才能創建一個zip文件。 雖然這個想法正在發揮作用,但我很快意識到它並非真正需要。
當打包程序嘗試一次打開整個文件然后壓縮它時,memorylimit只是一個問題。 幸運的是,一些聰明的人已經認為它更容易在塊中進行。
Asbjorn Grandt是創造這個拉鏈類的人之一,它非常易於使用並滿足您的需求。
首先,我創建了一個非常大的文件。 它的大小為500MB,里面有各種字母。 此文件可以立即返回處理,這會導致致命的內存限制錯誤。
<?php
$fh = fopen("largefile.txt", 'w');
fclose($fh);
$fh = fopen("largefile.txt", 'ab');
$size = 500;
while($size--) {
$l = chr(rand(97, 122));
fwrite($fh, str_repeat($l, 1024*1024));
}
fclose($fh);
?>
要使用zip類,我們會這樣做:
<?php
include('zip.php');
$zip = new Zip();
$zip->setZipFile("largefile.zip");
//the firstname is the name as it will appear inside the zip and the second is the filelocation. In my case I used the same, but you could rename the file inside the zip easily.
$zip->addLargeFile("largefile.txt", "largefile.txt");
$zip->finalize();
?>
現在我的服務器上只需幾秒鍾即可創建大型zip,結果是一個550KB的文件。
現在,如果出於某些奇怪的原因,您仍需要在多個Web請求中執行此操作,請告訴我們。 我仍然有我開始的代碼來做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.