Skip to content

Instantly share code, notes, and snippets.

@nmcgann
Created May 7, 2017 16:29
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 nmcgann/7fffba11cbe29282dd7334e9df28cdf3 to your computer and use it in GitHub Desktop.
Save nmcgann/7fffba11cbe29282dd7334e9df28cdf3 to your computer and use it in GitHub Desktop.
PHP Command line zip utility. Simply zips a directory structure into an archive. No bells or whistles.
<?php
/*
* Command line zip equivalent - very simple version that just zips a directory structure completely.
* No options!
* Useful when it is needed to build e.g. a Wordpress plugin zip archive, but the dev environment
* doesn't have zip - i.e. MINGW64 as bundled with Git - has unzip, but not zip.
*/
date_default_timezone_set('UTC');
error_reporting (E_ALL);
if ($argc < 3){
echo "Usage: php phpzip archive_name directory_to_zip\n";
exit(1);
}
if(!extension_loaded('zip')){
echo "Error: PHP Zip extension not loaded, cannot continue.\n";
exit(1);
}
//function to recursively add files and folders to zip
function folder_to_zip($folder, &$zip_obj) {
if (is_null($zip_obj)) {
throw new Exception("Error: No Zip class object provided.");
}
// ensure slash termination
$folder = rtrim($folder, '/') . '/';
// iterate through files and directories
$handle = @opendir($folder);
if($handle === false){
throw new Exception("Error: Cannot open '$folder'.");
}
while ($f = readdir($handle)) {
if ($f != "." && $f != "..") {
if (is_file($folder . $f)) {
$res = @$zip_obj->addFile($folder . $f);
if($res === false){
throw new Exception("Error: Failed to write file to archive.");
}
} elseif (is_dir($folder . $f)) {
// if dir, create a new dir in the zip
$res = @$zip_obj->addEmptyDir($folder . $f);
if($res === false){
throw new Exception("Error: Failed to create directory in archive.");
}
// ...and call the function again recursively
folder_to_zip($folder . $f, $zip_obj);
}
}
}
closedir($handle);
}
$z = new ZipArchive();
$res = @$z->open($argv[1], ZIPARCHIVE::OVERWRITE);
if($res === false){
echo("Error: Failed to open zip archive to write.\n");
exit(1);
}
try{
folder_to_zip($argv[2], $z);
$z->close();
}catch(Exception $ex){
echo $ex->getMessage()."\n";
$z->close();
exit(1);
}
//all good
exit(0);
/* end */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment