markf
markf

Reputation: 83

Recursively zip multiple folders

The following function works great, but it only zips the 1 folder. I need to zip several specific folders in the root of a site but not all of the rest.

Source: How to [recursively] Zip a directory in PHP?

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('\\', '/', 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();

Called with this:

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

Upvotes: 3

Views: 4395

Answers (1)

Alexey Gerasimov
Alexey Gerasimov

Reputation: 2141

If I understand you correctly, you can simply change your code to expect $source to be either string or array. Then you can loop through that array and add all desired folders and their sub-folders

Examples:

function Zip($source, $destination)
{
    if (is_string($source)) $source_arr = array($source); // convert it to array

    if (!extension_loaded('zip')) {
        return false;
    }

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

    foreach ($source_arr as $source)
    {
        if (!file_exists($source)) continue;
$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();

}

Zip might be empty of all specified paths are invalid but you can take care of that too.

Upvotes: 1

Related Questions