前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP对目录下的子目录及文件进行压缩并解压

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

原创
作者头像
Action
修改2021-05-12 17:07:51
1.6K0
修改2021-05-12 17:07:51
举报
文章被收录于专栏:WEB开发~WEB开发~

创建压缩类文件 zip.php

代码语言:txt
复制
<?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
代码语言:javascript
复制
<?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';
    }    

创建的目录结构如下

生成的结果

解压文件

代码语言:txt
复制
<?php

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建压缩类文件 zip.php
  • 测试
  • 解压文件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档