一、 引语
本人在做一个企业云盘项目当中,遇到一个文件在线解压缩的需求,查了网上很多资料,但都是只支持单一格式或部分格式,固创建了本工具类,对市面上主流的压缩格式进行集成支持,并且简单易用。
二、 功能
-
支持zip、rar、phar、tar、gz、bz2、7z格式的解压
-
支持对单文件、多文件、文件夹进行压缩成zip文件格式数据库连接池
三、 前置条件
-
安装php_zip插件:用于解压缩zip格式文件
-
安装php_rar插件:用于解压缩rar格式文件
-
安装php_phar插件:用于解压缩phar、tar、gz、bz2格式文件
-
安装p7zip p7zip-full软件:用于解压缩7z格式文件
四、 实现
class ZipUtil
{
/**
* 解压
* @param string $zipFilePath 压缩文件路径
* @param string $toDirPath 解压目录路径
* @return string
* @throws \Exception
*/
public static function extract(string $zipFilePath, string $toDirPath)
{
$toDirPath = rtrim($toDirPath, '/');
self::deleteDir($toDirPath, false);
if (!is_file($zipFilePath)) throw new \Exception('文件不存在。');
if (!is_dir($toDirPath)) {
mkdir($toDirPath, 0777, true);
}
$zipFilePathInfo = pathinfo($zipFilePath);
$zipExt = pathinfo($zipFilePath, PATHINFO_EXTENSION);
switch ($zipExt) {
case 'zip':
if (!class_exists('\ZipArchive')) throw new \Exception('未安装Zip插件。');
$zipArch = new \ZipArchive();
if ($zipArch->open($zipFilePath) !== true) throw new \Exception('解压失败。');
//$zipArch->extractTo($toDirPath); //这个中文会乱码
//解决中文会乱码
$fileNum = $zipArch->numFiles;
for ($i = 0; $i < $fileNum; ++$i) {
$statInfo = $zipArch->statIndex($i, \ZipArchive::FL_ENC_RAW);
$statInfo['name'] = self::convertToUtf8($statInfo['name']);
//print_r($statInfo);
if ($statInfo['crc'] === 0 && $statInfo['name'][strlen($statInfo['name']) - 1] === '/') {
$dirPath = $toDirPath . '/' . $statInfo['name'];
if (!is_dir($dirPath)) {
mkdir($dirPath, 0777, true);
}
} else {
copy('zip://' . $zipFilePath . '#' . $zipArch->getNameIndex($i), $toDirPath . '/' . $statInfo['name']);
}
}
$zipArch->close();
break;
case 'rar':
if (!class_exists('\RarArchive')) throw new \Exception('未安装Rar插件。');
$rarArch = \RarArchive::open($zipFilePath);
if ($rarArch =&