Created
March 28, 2015 03:37
-
-
Save thanhluu/c251c7aba2e87d746010 to your computer and use it in GitHub Desktop.
Zip All Files inside Folder via PHP
This file contains hidden or 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 | |
// 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