Skip to content

Instantly share code, notes, and snippets.

@steve-todorov
Last active December 17, 2015 12:19
Show Gist options
  • Save steve-todorov/5608950 to your computer and use it in GitHub Desktop.
Save steve-todorov/5608950 to your computer and use it in GitHub Desktop.
Create zip files.
<?php
function create_zip($path, $save_as)
{
if (!extension_loaded('zip'))
throw new ErrorException('Extension ZIP has not been compiled or loaded in php.');
else if(!file_exists($path))
throw new ErrorException('The file/path you want to zip doesn\'t exist!');
$zip = new ZipArchive();
if (!$zip->open($save_as, ZIPARCHIVE::CREATE))
throw new ErrorException('Could not create zip file!');
$ignore = array('.','..');
if($path == dirname($save_as))
$ignore[] = basename($save_as);
$path = str_replace('\\', '/', realpath($path));
if (is_dir($path)) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if( in_array(substr($file, strrpos($file, '/')+1), $ignore )) continue;
$file = realpath($file);
if (is_dir($file)) {
$zip->addEmptyDir(str_replace($path . '/', '', $file . '/'));
}
else if (is_file($file)) {
$zip->addFromString(str_replace($path . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($path)) {
$zip->addFromString(basename($path), file_get_contents($path));
}
return $zip->close();
}
$zip = create_zip('/path/to/save', '/path/to/save.zip');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment