Home > Backend Development > PHP Tutorial > How to Recursively Zip a Directory in PHP?

How to Recursively Zip a Directory in PHP?

DDD
Release: 2024-12-11 03:20:10
Original
965 people have browsed it

How to Recursively Zip a Directory in PHP?

How to [Recursively] Zip a Directory in PHP

The goal is to effectively zip a directory, including all its subdirectories and files, in PHP.

Approach Using PHP Zip Class

You can utilize the PHP Zip class to achieve this. The provided code offers a basic approach, but it only operates with individual files, not directories.

Working Code

To tackle this challenge, consider the following code:

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

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        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('\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = 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();
}
Copy after login

Usage:

Invoke the Zip function as shown here:

Zip('/folder/to/compress/', './compressed.zip');
Copy after login

This code recursively iterates through the specified source directory and its subdirectories, adding files and empty directories to the zip archive. Its operation is compatible with both Windows and Linux platforms.

The above is the detailed content of How to Recursively Zip a Directory in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template