How to zip a whole folder using PHP?

Spread the love

Sometimes, we want to zip a whole folder using PHP.

In this article, we’ll look at how to zip a whole folder using PHP.

How to zip a whole folder using PHP?

To zip a whole folder using PHP, we can use the ZipArchive class.

For instance, we write

$rootPath = realpath("folder-to-zip");

$zip = new ZipArchive();
$zip->open("file.zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file) {
    // Skip directories (they would be added automatically)
    if (!$file->isDir()) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        $zip->addFile($filePath, $relativePath);
    }
}

$zip->close();

to get the real path to our folder with

$rootPath = realpath('folder-to-zip');

Then we create the archive object with

$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

Next, we create the recursive directory iterator with

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
)

After that, we use a foreach loop to loop through the $files and add all the files to the archive.

We get the real file path of the file being looped through with

$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);

Next, we add the file to the zip file with

$zip->addFile($filePath, $relativePath);

After the loop is done, we use $zip->close(); to close the zip file object.

Conclusion

To zip a whole folder using PHP, we can use the ZipArchive class.

Leave a Reply

Your email address will not be published.