Skip to content

Instantly share code, notes, and snippets.

@german-bortoli
Created October 9, 2012 17:37
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 german-bortoli/3860238 to your computer and use it in GitHub Desktop.
Save german-bortoli/3860238 to your computer and use it in GitHub Desktop.
Zip folder
<?php
function zip_folder($source, $destination) {
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
/**
* USAGE
**/
//$bck_date = date('Y.m.d');
//$bck_name = "backup-{$bck_date}";
//zip_folder('./', "./{$bck_name}.zip");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment