Skip to content

Instantly share code, notes, and snippets.

@progmult
Forked from menzerath/backup.php
Last active August 8, 2018 03:01
Show Gist options
  • Save progmult/8264ccd186d6557579a624443cdf6481 to your computer and use it in GitHub Desktop.
Save progmult/8264ccd186d6557579a624443cdf6481 to your computer and use it in GitHub Desktop.
PHP: Recursively Backup Files & Folders to ZIP-File
<?php
/*
* PHP: Recursively Backup Files & Folders to ZIP-File
* MIT-License - Copyright (c) 2012-2017 Marvin Menzerath
*/
// Make sure the script can handle large folders/files
ini_set('max_execution_time', 600);
ini_set('memory_limit','1024M');
// Start the backup!
zipData('/path/to/folder', '/path/to/backup.zip');
echo 'Finished.';
// Here the magic happens :)
function zipData($source, $destination) {
if (extension_loaded('zip')) {
if (file_exists($source)) {
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
$source = realpath($source);
if (is_dir($source)) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = realpath($file);
if (is_dir($file)) {
if ($file != dirname($source)) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
} else if (is_file($file)) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} else if (is_file($source)) {
$zip->addFromString(basename($source), file_get_contents($source));
}
}
return $zip->close();
}
}
return false;
}
?>
@progmult
Copy link
Author

fix empty parent folder adding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment