Created
January 28, 2017 16:27
-
-
Save brutaldesign/7123bc736360406832b8c783f4db71a7 to your computer and use it in GitHub Desktop.
Zip a folder
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
/** | |
* Zip a folder | |
* | |
* @param string $src path to folder path/folder | |
* @param string $dest destination name path/folder.zip | |
* @see http://stackoverflow.com/questions/4914750/how-to-zip-a-whole-folder-using-php | |
*/ | |
function zipit( $src, $dest = null ) { | |
// Get real path for our folder | |
$path = realpath( $src ); | |
if ( ! $dest ) { | |
$dest = $src . '.zip'; | |
} | |
// Initialize archive object | |
$zip = new ZipArchive(); | |
$zip->open( $dest, ZipArchive::CREATE | ZipArchive::OVERWRITE); | |
// Create recursive directory iterator | |
/** @var SplFileInfo[] $files */ | |
$files = new RecursiveIteratorIterator( | |
new RecursiveDirectoryIterator( $path ), | |
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 | |
$file_path = $file->getRealPath(); | |
$relative_path = substr( $file_path, strlen( $path ) + 1); | |
// Add current file to archive | |
$zip->addFile( $file_path, $relative_path ); | |
} | |
} | |
// Zip archive will be created only after closing object | |
$zip->close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment