Skip to content

Instantly share code, notes, and snippets.

@pavr0m
Created March 2, 2020 21:55
Show Gist options
  • Save pavr0m/1cd1d5a20af19d97042a422c3564f8d4 to your computer and use it in GitHub Desktop.
Save pavr0m/1cd1d5a20af19d97042a422c3564f8d4 to your computer and use it in GitHub Desktop.
Zip files recursively using ZipArchive class
<?php
$rootPath = realpath('folder');
$zip = new ZipArchive();
$zip->open('archive.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())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
print_r('Done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment