进行网站备份的时候我们经常需要将文件打包,zip格式是常用的格式,而且zip在php下面使用非常方便。
下面一个文件实现目录的zip压缩和对压缩文件的解压。
官方手册:https://www.php.net/manual/en/class.ziparchive.php
效果:

全部代码:
<?php
/**
* Created by 1076963452@qq.com
* User: BriskLan
* Date: 2019/7/13 16:08
*/
/**
* @param $needZipPath string 需要备份的路径目录
* @param $backupPath string zip文件存放目录
* @param string $backupFileName zip文件名称
* @param string $skipDir 需要跳过的目录
* @return bool
*/
function zip_encode($needZipPath,$backupPath,$backupFileName='',$skipDir='web_backup')
{
if (!class_exists('ZipArchive')){
return false;
}
$backupFileName = $backupFileName ? $backupFileName : date('Y.m.d.H').'.zip';
//实例化ZIP类
$zip = new ZipArchive();
//创建文件或者重写文件
$zip->open($backupPath.$backupFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// 创建递归目录迭代器
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($needZipPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
//todo 排除掉备份存放目录,最好就是放在非需要备份的目录外层
if (stripos($name,$skipDir)){
continue;
}
// 跳过目录(它们将自动添加)
if (!$file->isDir()) {
// 获取当前文件的实际路径和相对路径
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($needZipPath) + 1);
// 将当前文件添加到压缩包
$zip->addFile($filePath, $relativePath);
}
}
// 只有在关闭对象后才能创建zip文件!
$zip->close();
if (file_exists($backupPath.$backupFileName)){
return true;
}
return false;
}
/**
* 解压zip文件
* @param $filePath string 需要解压的文件路径
* @param $extractToPath string 解压后存放的路径,必须先建立
* @return bool
*/
function zip_decode($filePath,$extractToPath)
{
if (class_exists('ZipArchive')){
$zip = new ZipArchive ;
if ( $zip -> open ($filePath ) === TRUE ) {
$zip -> extractTo ( $extractToPath );
$zip -> close ();
return true;
}
}
return false ;
}
//压缩
$needZipPath = realpath(DIR_ROOT.'/');
$backupPath = DIR_ROOT . '/web_backup/web/';
$backupFileName = date('Y.m.d.H').'.zip';
zip_encode($needZipPath,$backupPath,$backupFileName,'web_backup');
//解压
zip_decode(DIR_ROOT . '/web_backup/web/2019.07.13.17.zip',DIR_ROOT.'/web_backup/ext/');