美文网首页
php对目录下的子目录及文件进行压缩,并解压

php对目录下的子目录及文件进行压缩,并解压

作者: 程序员Ameng | 来源:发表于2020-12-05 16:04 被阅读0次

    创建压缩类文件 zip.php

    <?php
    
    class Zip{
      
      /**
       * Zip a folder (include itself).
       * Usage:
       *   Zip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
       *
       * @param string $sourcePath Path of directory to be zip.
       * @param string $outZipPath Path of output zip file.
       */
      public static function zipDir($sourcePath, $outZipPath)
      {
    
        $pathInfo = self::myPathInfo($sourcePath);
        $parentPath = $pathInfo['dirname'];
        $dirName = $pathInfo['basename'];
        $sourcePath=$parentPath.'/'.$dirName;//防止传递'folder' 文件夹产生bug
        $z = new \ZipArchive();
        $z->open($outZipPath, \ZIPARCHIVE::CREATE);//建立zip文件
        $z->addEmptyDir($dirName);//建立文件夹
        self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
        $z->close();
      }
    
      private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
        $handle = opendir($folder);
        while (false !== $f = readdir($handle)) {
          if ($f != '.' && $f != '..') {
            $filePath = "$folder/$f";
            // Remove prefix from file path before add to zip.
            $localPath = substr($filePath, $exclusiveLength);
            if (is_file($filePath)) {
              $zipFile->addFile($filePath, $localPath);
            } elseif (is_dir($filePath)) {
              // 添加子文件夹
              $zipFile->addEmptyDir($localPath);
              self::folderToZip($filePath, $zipFile, $exclusiveLength);
            }
          }
        }
        closedir($handle);
      }
    
      private static function myPathInfo($filepath)  
      {  
          $pathParts = array();  
          $pathParts ['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath, '/')),"/")."/";  
          $pathParts ['basename'] = ltrim(substr($filepath, strrpos($filepath, '/')),"/");  
          $pathParts ['extension'] = substr(strrchr($filepath, '.'), 1);  
          $pathParts ['filename'] = ltrim(substr($pathParts ['basename'], 0, strrpos($pathParts ['basename'], '.')),"/");  
          return $pathParts;  
      } 
    }
    

    测试

    1. 将test文件夹进行压缩,生成的文件test.zip,放入zip目录
    2. 创建test.php
    <?php
        require_once('zip.php');
        $zip = new Zip();
       
        $sourceDir = 'D:/phpstudy_pro/WWW/test/zip/test';
        $outZipPath = 'D:/phpstudy_pro/WWW/test/zip/zip/test.zip';
        $zip->zipDir($sourceDir, $outZipPath);
        if(file_exists($outZipPath)){
            echo 'success';
        }else{
            echo 'fail';
        }
    

    创建的目录结构如下

    生成的结果

    解压文件

    <?php
    
    $zip = new \ZipArchive();
    if ($zip->open('test.zip') === TRUE){
        //假设解压缩到在当前路径下demo文件夹
        $zip->extractTo('demo');
    }
    $zip->close();

    相关文章

      网友评论

          本文标题:php对目录下的子目录及文件进行压缩,并解压

          本文链接:https://www.haomeiwen.com/subject/rtugwktx.html