When I create a zip file of a directory with a lar

2019-08-23 23:30发布

问题:

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');

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?

回答1:

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

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