发布于2022年10月15日2年前 <?php use ZipArchive; class Zip { /** * @var array $files 需要压缩的文件或文件夹 */ public $files = []; /** * 排除的文件 */ public $notFile = []; /** * 压缩或者解压密码 */ public $passowrd = null; //压缩包名字及输出地址 public $zipName = 'package.zip'; //检测的根目录,默认为APP根目录 public $rootPath = AR; private function addDir($folder, $zipFile, $rootPath, $folderSub = null) { // $folder = $this->rootPath . $folderb; if (is_dir($folder)) { $handle = opendir($folder); while (false !== $f = readdir($handle)) { if ($f != '.' && $f != '..') { // Remove prefix from file path before add to zip. $localPath = substr($filePath, $rootPath); if (is_file($filePath)) { $this->addFile($filePath, $localPath, $zipFile); } elseif (is_dir($filePath)) { // Add sub-directory. $zipFile->addEmptyDir($localPath); $this->addDir($filePath, $zipFile, $rootPath, $folderSub); } } } closedir($handle); } else { $this->addFile($folder, $folderSub, $zipFile); } } private function addFile($filePath, $localPath, $zipFile) { $zipFile->addFile($filePath, $localPath); if ($this->passowrd) { $zipFile->setEncryptionName($localPath, ZipArchive::EM_AES_256); } } /** * 打包成ZIP */ public function zip() { $zip = new ZipArchive(); $zip->open(AR . $this->zipName, ZIPARCHIVE::CREATE); if ($this->passowrd) { $zip->setPassword($this->passowrd); } foreach ($this->files as $row) { $pathInfo = pathinfo($this->rootPath . $row); is_dir($this->rootPath . $row) ? $zip->addEmptyDir($pathInfo['basename']) : ''; $z = $this->addDir($this->rootPath . $row, $zip, strlen($pathInfo['dirname'] . '/'), $row); } foreach ($this->notFile as $row) { $zip->deleteName($row); } $zip->close(); return $z; } /** * 解压压缩包 */ public function uzip($file, $path) { $zip = new ZipArchive(); $this->passowrd ? $zip->setPassword($this->passowrd) : ''; $zip->open($file); $zip->extractTo($path); $zip->close(); } } 为防止网络爬虫,已删除关键代码,如有需要请发送博客地址到下边提示的邮箱里
创建帐户或登录后发表意见