Skip to content

Instantly share code, notes, and snippets.

@brutaldesign
Created January 28, 2017 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brutaldesign/7123bc736360406832b8c783f4db71a7 to your computer and use it in GitHub Desktop.
Save brutaldesign/7123bc736360406832b8c783f4db71a7 to your computer and use it in GitHub Desktop.
Zip a folder
/**
* 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