php有自带的扩展类ZipArchive可以压缩/解压缩
压缩文件可以分为3类:
- 单文件压缩成一个zip包
- 多文件压缩成一个zip包
- 文件夹压缩成一个zip包
单文件压缩
// 单文件
$zip = new ZipArchive;
$zip_time = time().".zip"; // 压缩的目录名
$zip_filename = "../alg/".$zip_time; // 指定一个压缩包地址
$zip->open($zip_filename, ZIPARCHIVE::CREATE); // 打开压缩包,没有则创建
// 参数1是要压缩的文件,参数2为压缩后,在压缩包中的文件名「这里我们把 demo1.php 文件压缩,压缩后的文件为 dd.php」,如果需要的压缩后的文件跟原文件名一样 addFile() 的第二个参数可以改为 basename("../alg/demo1.php"),也就是原文件所在的路径
$zip->addFile("../alg/demo1.php",basename("dd.php"));
$rs = $zip->close();
var_dump($rs);
多文件压缩
// 压缩多个文件
$fileList = array(
"../alg/demo1.php",
"../alg/demo2.php",
);
$filename = "../alg/multiple_files.zip"; // 压缩包所在的位置路径
$zip = new ZipArchive();
$zip->open($filename,ZipArchive::CREATE); //打开压缩包
foreach($fileList as $file){
$zip->addFile($file,basename($file)); //向压缩包中添加文件
}
$zip->close(); //关闭压缩包
压缩一个目录
/**
* 文件打包
* @param $strPath
* @param ZipArchive $pZip
* @return bool
*/
public function addFileToZip($strPath, ZipArchive $pZip)
{
$handler = opendir($strPath); //打开当前文件夹由$path指定。
while (($filename = readdir($handler)) !== false) {
if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’,不要对他们进行操作
if (is_dir($strPath. "/" . $filename)) {// 如果读取的某个对象是文件夹,则递归
$this->addFileToZip($strPath. "/" . $filename, $pZip);
} else { //将文件加入zip对象
if($filename == 'background.jpg')
continue;
//参数filename:要添加的文件的路径
//参数localname:如果提供的话,这是ZIP归档文件中的本地名称,它将覆盖filename
$pZip->addFile($strPath. "/" . $filename, $filename);
}
}
}
@closedir($strPath);
return true;
}
$strPath = base_path().'/storage/images/qrcode.zip';
try
{
$pZip = new ZipArchive();
$pZip->open($strPath, ZipArchive::CREATE);
$strFilePath = base_path().'/storage/images/qrcode/';
$this->addFileToZip($strFilePath, $pZip);
$pZip->close();
}catch (Exception $e)
{
throw new BusinessException('文件打包异常:'.$e->getMessage());
}