This might not be the best code for this, yet its the most concise code I found that doesnt require a bunch of additional classes. I found this online dont remember where and I added a few lines cause of errors. If you get memory errors you can increase the memory (ini_set(‘memory_limit’, ‘300M’).
<?php
ini_set(‘memory_limit’, ‘300M’);
$archive = ‘zipbackup.zip’; // File Name ;
$source = ‘wp-content/gallery/’; // Path To the folder;
$destination = ‘zipbackup.zip’; // Path to the file and file name ;
$include_dir = false;
if(file_exists($destination)) {
unlink($destination);
}
ob_start();
if (!extension_loaded(‘zip’) || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive;
if (!$zip->open($archive, ZipArchive::CREATE)) {
return false;
}
$source = str_replace(‘\\’, ‘/’, realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode(“/”,$source);
$maindir = $arr[count($arr)- 1];
$source = “”;
for ($i=0; $i < count($arr) – 1; $i++) {
$source .= ‘/’ . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
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 . ‘/’));
//echo “added directory: ” . $file . “<br>”;
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . ‘/’, ”, $file), file_get_contents($file));
//echo “added image: ” . $file . “<br>”;
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
echo ‘ location.replace(“backup.zip”); ‘; //name of zip here
?>


You must be logged in to post a comment.