PHP执行文件的压缩和解压缩方法

  •   
  • 1356
  • PHP
  • 0
  • super_dodo
  • 2021/09/07

最近的项目中需要用到PHP去处理文件的压缩和解压缩,网上找了一下方法大概如下。


<?php
/**
 * PHP处理文件的压缩和解压缩
 */

class FileZip
{

    /**
     * 压缩文件
     * @param array $files 待压缩文件 array('d:/test/1.txt','d:/test/2.jpg');【文件地址为绝对路径】
     * @param string $filePath 输出文件路径 【绝对文件地址】 如 d:/test/new.zip
     * @return string|bool
     */
    public function zip($files, $filePath)
    {
        //检查参数
        if (empty($files) || empty($filePath)) {
            return false;
        }

        //压缩文件
        $zip = new \ZipArchive();
        $zip->open($filePath, \ZipArchive::CREATE);
        foreach ($files as $key => $file) {
            //检查文件是否存在
            if (!file_exists($file)) {
                return false;
            }
            $zip->addFile($file, basename($file));
        }
        $zip->close();

        return true;
    }

    /**
     * zip解压方法
     * @param string $filePath 压缩包所在地址 【绝对文件地址】d:/test/123.zip
     * @param string $path 解压路径 【绝对文件目录路径】d:/test
     * @return bool
     */
    public function unzip($filePath, $path)
    {
        if (empty($path) || empty($filePath)) {
            return false;
        }

        $zip = new \ZipArchive();
        if ($zip->open($filePath) === true) {
            $zip->extractTo($path);     //提取全部文件
            //$zip->extractTo('/my/destination/dir/', array('aa.gif', 'bb.php'));//提取部分文件
            $zip->close();
            return true;
        } else {
            return false;
        }
    }

}