Skip to content

Instantly share code, notes, and snippets.

@thanhluu
Created March 28, 2015 03:37
Show Gist options
  • Save thanhluu/c251c7aba2e87d746010 to your computer and use it in GitHub Desktop.
Save thanhluu/c251c7aba2e87d746010 to your computer and use it in GitHub Desktop.
Zip All Files inside Folder via PHP
<?php
// increase script timeout value
ini_set("max_execution_time", 300);
// create object
$root = dirname(__FILE__);
$folder = 'folder';
$zip = new ZipArchive();
// open archive
if ( $zip->open( $root . '/test-zip.zip', ZIPARCHIVE::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
die ("Could not open archive");
}
// Create recursive directory iterator
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator( $root . '/' . $folder )
);
foreach ($files as $name => $file) {
$filePath = str_replace( $root . '/' , '', $file->getRealPath() );
if ( ! $filePath || $filePath == $root ) {
continue;
}
$newPath = str_replace( $folder . '/', '', $filePath );
if ( $newPath == $folder || ! $newPath ) {
continue;
}
if ( is_dir($filePath) ) {
$zip->addEmptyDir( $newPath );
} else {
// Add current file to archive
$zip->addFile( $filePath, $newPath );
}
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment