我的 PHP zip 函数占用了太多内存

My PHP zip function is using too much memory

我正在尝试使用下面的函数来压缩一个 551 MB 的文件,但是没有足够的内存来 运行。我用它来压缩其他文件并且它工作正常所以我认为它与文件的大小有关。

    function Zip($source, $destination)
{
    global $latest_filename;
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
        return false;
    }

    $source = str_replace('\', '/', realpath($source));

    if (is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file) {
            $file = str_replace('\', '/', realpath($file));

            if (is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            } else if (is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } else if (is_file($source) === true) {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

这是我收到的错误:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to  allocate 577311064 bytes)

感谢您对此的任何帮助。

哎呀,我想知道你认为它与文件大小有什么关系:'^

现在说真的,php.ini 有一个指令,您可以修改它以允许进程有更多内存。只需打开它并搜索 512 我猜,增加它。

如果您没有管理员权限,请尝试将此代码插入 ini_set('memory_limit', '1024M')

但没有承诺。

如果您不能增加分配给脚本的 RAM,您可能想看看如果使用 exec() 并直接使用操作系统的解压缩,使用的内存是否更少。不过,我不希望看到使用的内存少于 zip 文件的大小。在阅读 zip 的内容并将它们分成与可用内存匹配的块后,您还可以考虑分批解压缩内容。

提高内存限制有时是解决问题的正确方法,但它不会扩展。当然,您 不应该通过更改 php.ini 中的内存限制来解决单个脚本的问题!

如果您的容量为 500Mb,那么您已经接近系统能够提供的容量极限。

查看您的脚本,您的方法没有明显的错误 - 可能是 zip 文件是在内存中构建的,或者有什么东西正在泄漏。测试是哪种情况相当容易。泄漏可能会通过升级修复,但也可能不会。

最快的解决方案是将代码替换为:

function Zip($source, $destination)
{
   if (!is_readable($source) || ! is_writeable(dirname($dest)) ||
         (file_exists($dest) && !is_file($dest))) {
       // really you should capture some more specific information
       // in your excaption handling
       return false;
   }
   $output='';
   $returnv=true;
   exec("zip -r $destination $source", $output, $returnv);
   return !$returnv;
}

感谢您对这个问题的所有答复,我决定做的是创建一个新的压缩函数,该函数不使用 'file_get_contents',因为这会耗尽所有内存。

这是我的新功能

function zip2 ($zipname){

    $zip = new ZipArchive();

    $zip->open("" .$zipname. ".zip", ZipArchive::CREATE);

    $files = scandir("" .$zipname. "");
    unset($files[0], $files[1]);

    foreach ($files as $file){
        $zip->addFile("" .$zipname. "/{$file}");
    }
    $zip->close();
}

谢谢

科林