Created
March 2, 2020 21:55
-
-
Save pavr0m/1cd1d5a20af19d97042a422c3564f8d4 to your computer and use it in GitHub Desktop.
Zip files recursively using ZipArchive class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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