Skip to content

Instantly share code, notes, and snippets.

Created May 7, 2017
What would you like to do?
PHP Command line zip utility. Simply zips a directory structure into an archive. No bells or whistles.
* 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.
error_reporting (E_ALL);
if ($argc < 3){
echo "Usage: php phpzip archive_name directory_to_zip\n";
echo "Error: PHP Zip extension not loaded, cannot continue.\n";
//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);
$z = new ZipArchive();
$res = @$z->open($argv[1], ZIPARCHIVE::OVERWRITE);
if($res === false){
echo("Error: Failed to open zip archive to write.\n");
folder_to_zip($argv[2], $z);
}catch(Exception $ex){
echo $ex->getMessage()."\n";
//all good
/* end */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment