当我在 PHP 中创建一个带有大 zip 文件的目录的 zip 文件时,我面临内存限制 [英] When I create a zip file of a directory with a large zip file in PHP, I am facing a memory limit

查看:21
本文介绍了当我在 PHP 中创建一个带有大 zip 文件的目录的 zip 文件时,我面临内存限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 WordPress 插件代码遇到内存限制错误.

我的代码:

I am facing a memory limit error in my WordPress plugin code.

My Code:

function zipData($source, $destination) {
    if (extension_loaded('zip')) {
        if (file_exists($source)) {
            $zip = new ZipArchive();
            if ($zip -> open($destination, ZipArchive::CREATE) === TRUE)     {
                $source = realpath($source);
                if (is_dir($source)) {
                    $iterator = new RecursiveDirectoryIterator($source);

                    $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
                    $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
                    foreach ($files as $file) {
                        $file = realpath($file);
                        if (is_dir($file)) {
                            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                        } else if (is_file($file)) {
                            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                        }
                    }
                } else if (is_file($source)) {
                    $zip->addFromString(basename($source), file_get_contents($source));
                }
            }
            return $zip->close();
        }
    }
    return false;
}

ini_set('max_execution_time', 600);
ini_set('memory_limit','1024M');
zipData($upload_dir['basedir'], $upload_dir['basedir'].'/Jincowboy/JinBackupMedia'. time() .'.zip');

我遇到了内存限制,所以我检查了 Google.

我发现需要生成流 zip 文件来避免内存限制,但我无法确认这一点.

我希望我的代码绕过此内存限制,并允许基于包含大文件的目录创建 zip 文件.

我该如何解决这个问题?

I encountered a memory limit so I checked Google.

I found that stream zip file generation is needed for avoiding the memory limit, but I couldn't confirm about this.

I want my code to bypass this memory limit and allow creation of a zip file based on a directory with large files.

How can I fix this?

推荐答案

你可以试试 https://github.com/Grandt/PHPZip 支持使用流数据创建 ZIP 文件(大量降低内存使用量).

You can try https://github.com/Grandt/PHPZip which supports creating ZIP files with streaming data (lowering memory usage by a lot).

并且有很多关于压缩流的 stackoverflow 帖子,其中包含大量答案.

And there are plenty of stackoverflow posts about zipping with streams with a pletora of answers.

这篇关于当我在 PHP 中创建一个带有大 zip 文件的目录的 zip 文件时,我面临内存限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆