Skip to content

Instantly share code, notes, and snippets.

@ashokmhrj
Last active June 10, 2016 06:18
Show Gist options
  • Save ashokmhrj/6f131cc5afe8da5fe71f to your computer and use it in GitHub Desktop.
Save ashokmhrj/6f131cc5afe8da5fe71f to your computer and use it in GitHub Desktop.
Archive folder php
<?php
/**
* PHP script to zip folder using RecursiveDirectoryIterator PHP function
*/
// Get real path for folder
$folder_to_zip = realpath("path-to-folder");
//saving zip
$zipname = "zip-file-name.zip";
// we are using try and catch
// you can run the script without the try..catch
try{
// Initialize archive object
$zip = new ZipArchive();
$zip->open( $zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder_to_zip), 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($folder_to_zip) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
} // if ends
} // foreach ends
echo "zip is generated";
} catch( Exception $e ){
// catch message for unable to generate zip
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment