Created
April 2, 2013 11:22
-
-
Save steve-todorov/5291540 to your computer and use it in GitHub Desktop.
Create zip files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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/zip/', '/path/to/save.zip'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment