php压缩解压类

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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容