我想备份我的网站文件,并想要排除一些文件夹/文件。 我在一篇较旧的文章中寻找了一个解决方案,并按照下面的说明调整了一下:
<?php
/*
* PHP: Recursively Backup Files & Folders to ZIP-File
* (c) 2012-2014: Marvin Menzerath - http://menzerath.eu
* contribution: Drew Toddsby
*/
// Make sure the script can handle large folders/files
ini_set('max_execution_time', 600);
ini_set('memory_limit','1024M');
$dir = '/home/user10/public_html';
$HKfilename = date("Y-m-d-H-i");
$saveto = "/home/user10/public_ftp/file_bkup-$HKfilename.zip";
$exclude = array("$dir/cache","$dir/images", "$dir/media");
// Start the backup!
zipData($dir, $saveto, $exclude);
echo 'Files backup created: file_bkup-$HKfilename.zip';
// Here the magic happens :)
function zipData($source, $destination, $exclude) {
if (extension_loaded('zip')) {
if (file_exists($source)) {
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
$source = realpath($source);
if (is_dir($source)) {
$iterator = new RecursiveDirectoryIterator($source);
// skip dot files while iterating
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
if ( in_array($file, $exclude) ) {
continue;
}
if ( is_file($file) ) {
$p = pathinfo($file);
if ( in_array($p['dirname'], $exclude) ) {
continue;
}
}
$file = realpath($file);
if (is_dir($file)) {
$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;
}
我在执行脚本时遇到错误。
[15-Dec-2017 12:17:02] PHP Fatal error: Call to undefined method RecursiveDirectoryIterator::setFlags() in /home/user10/public_ftp/filebackup.php on line 32
如果我评论此代码,
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
生成zip文件,文件名为file_bkup-2017-11-22-20-39.zip.KDzpTi(每次尝试时最后6个字符更改)。但是,此zip文件不包含所有文件/文件夹。此外,此zip文件包含在exclude array。
中指定的文件夹