PHP使用ZipArchive压缩、解压缩、加密压缩包等
<?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(); } }
为防止网络爬虫,已删除关键代码,如有需要请发送博客地址到下边提示的邮箱里
本文来自博客园,作者:小枫同学,除网络转载的部分,其他版权属于作者和博客园所有,未经作者或博客园许可,禁止转载、复制、重新发布完整或者部分文字、代码、图片等信息,否则将保留追究法律责任的权利(如博客侵权了您的作品,本人再次表示抱歉,请将原创地址发送至下文邮箱,核实后立刻删除。)。查阅文章的同学,由于网络爬虫严重,有些代码并不会完整贴出来或者存在bug,不过你可以发送邮件到xfstune@126.com获取新代码,记得附上文章链接
分类:
code
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术