Zip Multiple Folders in PHP: A Comprehensive Tutorial

You'll learn how to use the ZipArchive class to create and extract zip files, as well as how to recursively add multiple folders to a single zip archive.

Here's an example code for zipping multiple folders using PHP's ZipArchive class:

 // create a new ZipArchive object
$zip = new ZipArchive();

// set the name of the zip file
$zipname = 'example.zip';

// open the zip file for writing
if ($zip->open($zipname, ZipArchive::CREATE) !== TRUE) {
    die('Error: Cannot create zip file');
}

// list of folders to zip
$folders = array('folder1', 'folder2', 'folder3');

// add each folder and its contents to the zip file
foreach ($folders as $folder) {
    // get the real path of the folder
    $realpath = realpath($folder);

    // add the folder and its contents to the zip file
    $zip->addEmptyDir($folder);
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($realpath),
        RecursiveIteratorIterator::LEAVES_ONLY
    );
    foreach ($files as $file) {
        if (!$file->isDir()) {
            $filepath = $file->getRealPath();
            $relativepath = substr($filepath, strlen($realpath) + 1);
            $zip->addFile($filepath, $folder . '/' . $relativepath);
        }
    }
}

// close the zip file
$zip->close();

echo 'Zip file created successfully!';

In this code, we first create a new ZipArchive object and specify the name of the zip file we want to create. We then open the zip file for writing using the open method.

We have an array of folders that we want to add to the zip file. We loop through each folder, use the addEmptyDir method to create a new directory in the zip file, and then add each file in the folder to the zip file using the addFile method.

Finally, we close the zip file and output a message to the user indicating that the zip file was created successfully.