在@ user2019515回答之后,我需要处理存档中的排除项。这是带有示例的结果函数。
邮编功能:
function Zip($source, $destination, $include_dir = false, $exclusions = false){
// Remove existing archive
if (file_exists($destination)) {
unlink ($destination);
}
$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);
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){
// Ignore "." and ".." folders
$file = str_replace('\\', '/', $file);
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))){
continue;
}
// Add Exclusion
if(($exclusions)&&(is_array($exclusions))){
if(in_array(str_replace($source.'/', '', $file), $exclusions)){
continue;
}
}
$file = realpath($file);
if (is_dir($file) === true){
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} elseif (is_file($file) === true){
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} elseif (is_file($source) === true){
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
如何使用它 :
function backup(){
$backup = 'tmp/backup-'.$this->site['version'].'.zip';
$exclusions = [];
// Excluding an entire directory
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('tmp/'), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file){
array_push($exclusions,$file);
}
// Excluding a file
array_push($exclusions,'config/config.php');
// Excluding the backup file
array_push($exclusions,$backup);
$this->Zip('.',$backup, false, $exclusions);
}