class PhpZip
{
/**
* 解压文件
* @param string $filePath 文件路径
* @param string $path 解压路径
* @throws Exception
*/
public static function uzip(string $filePath, string $path): void
{
if (empty($path) || empty($filePath)) {
throw new \Exception('文件路径或解压路径为空');
}
$zip = new \ZipArchive();
if (true === $zip->open($filePath, \ZipArchive::CREATE)) {
$zip->extractTo($path);
$zip->close();
} else {
throw new \Exception('打开文件失败');
}
}
/**
* 压缩文件
* @param string $filePath 压缩文件路径
* @param array $files 文件
* @param bool $isBaseName 是否basename
* @throws Exception
*/
public static function zip(string $filePath, array $files, bool $isBaseName = true): void
{
//检查参数
if (empty($files) || empty($filePath)) {
throw new \Exception('文件路径或解压路径为空');
}
//压缩文件
$zip = new ZipArchive();
if (true !== $zip->open($filePath, ZipArchive::CREATE)) {
throw new \Exception('打开文件失败');
}
foreach ($files as $key => $file) {
//检查文件是否存在
if (!file_exists($file)) {
$zip->close();
throw new \Exception('文件不存在:' . $file);
}
if ($isBaseName) {
$zip->addFile($file, basename($file));
} else {
$zip->addFile($file, $file);
}
}
$zip->close();
}
}
php压缩解压类
于 2022-07-21 14:29:43 首次发布