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

How to Recursively Zip a Directory in PHP?

DDD
DDDOriginal
2024-12-11 03:20:10963browse

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();
}

Usage:

Invoke the Zip function as shown here:

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

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!

Statement:
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