12

我有一些文件夹,其中包含用户生成的图像,这些图像变得相当大。尝试压缩这些文件时,我收到大约 1.5 gig 大小的 zip 文件的错误。

我的问题与内存有关,我认为 php 将 zip 和所有图像都保存在内存中。我有一个可能的解决方案是在上传时将每个图像发送到 zip 文件以及相应的文件夹,这似乎到目前为止有效,但 zip 文件大小的限制是什么,从我能找到的 4 GB 左右。这如何影响/与服务器上的 ram 数量相互作用?\并且限制实际上是 4gb 还是我可以无限期地继续将文件添加到 zip 或者我应该让脚本检查 zip 的大小以及它是否超过 X gigs 重命名它并创建一个新的 zip。我搜索了谷歌并阅读了文档,但发现了相互矛盾的信息或不完整的信息,因此我正在寻找一些明确的答案和建议。谢谢

4

3 回答 3

16

In case you still want to use the PHP ZipArchive, there are a few things you can do to prevent certain server/OS limitations:

  • Memory Although it might seem obvious in your case, i have seen many examples on how to use ZipArchive that use addFromString to add a new File to the archive. DON'T! This will allocate memory to open the file and store its content in it, which will make you run out of memory fast, use addFile instead. Make also sure that you free all the memory you don't need.

  • Execution time Increase the maximum execution time for your script, either via the php.ini, or with ini_set (e.g. ini_set('max_execution_time', 600); to have a maximum execution time of 10min)

  • File Handles Some OS have limits on the number of open files which can cause a problem because PHP only adds the files to the zip once you close the zip file. To prevent problems with the number of open files just close and reopen the zip file every x files (e.g. every 1000), this will force PHP to compress and add the files already assigned to the archive.

  • File Size There may be some file size limitations of the OS, a bigger file also means that PHP needs more memory to manage it, so i personally prefer to use a maximum file size after which i just open a new zip file using an index number. If the exact file size does not matter to you, you can just count the size of the files going into the archive and then switch after you reach a certain limit, or you can close the archive every x files and check its size on disk to decide wether to start a new archive or not (remember, the files get only compressed once you close the archive)

I personally like to limit the filesize by getting the size of the files going into the archive and applying a likely compression factor to it to see when the maximum archive size will probably be reached (jpg files ~0.9, zip files = 1, text files ~0.10, ...) and then switch to the next volume.

于 2014-03-25T15:19:58.003 回答
3

使用 php exec 并在命令行调用 zip 工具

 exec("tar -zcvf archive.tar.gz /folder/tozip");

确保执行 php 文件的用户有权访问您要压缩的文件夹

并注意注入代码。

于 2013-04-20T16:25:49.123 回答
1

由于流或内存可能仍在使用中,您必须在每个/某些文件之后从内存中“刷新”存档:

$zip->close();
unset($zip);
$zip = new ZipArchive;
$zip->open("arch.zip");
于 2018-06-15T12:37:04.077 回答