123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace app\common\components;
- use Yii;
- /*
- * $res = new MakeZip($dir,$zipName);
- *@ $dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt'
- *@ $zipName是压缩后的压缩包名称,可使用路径,例 'a/test.zip'或者'test.zip'
- **/
- class Dozip {
- private $_dir;
- private $_zipDir;
- private $_zipName;
- public function __construct($dir,$zipName) {
- $this->_dir = $dir;
- $this->_zipDir = basename($dir);
- $this->_zipName = $zipName;
- $this->mkdirs();
- $this->creat();
- }
- //检测并生成目录
- private function mkdirs() {
- if (!is_dir(dirname($this->_zipName))) {
- $arr = explode('/', dirname($this->_zipName));
- $arrs = '';
- foreach($arr as $value) {
- if (!is_dir($arrs.$value)) {
- if (!!mkdir($arrs.$value)) {
- $arrs .= $value.'/';
- }
- }
- }
- }
- }
- //生成Zip压缩包
- private function creat() {
- $zip = new \ZipArchive;
- if (is_dir($this->_dir)) {
- $this->readDir($this->_dir,$files);
- if ($zip->open($this->_zipName,\ZipArchive::OVERWRITE|\ZipArchive::CREATE)) {
- foreach ($files as $value) {
- preg_match('/\/('.$this->_zipDir.'\/.*)/', $value, $match);
- if (is_dir($value)) {
- $zip->addEmptyDir($value, $match[1]);
- } else {
- $zip->addFile($value, $match[1]);
- $zip->renameName($value,$this->_zipDir);
- }
- }
- $zip->close();
- }
- } else {
- if ($zip->open($this->_zipName,\ZipArchive::OVERWRITE|\ZipArchive::CREATE)) {
- $zip->addFile($this->_dir, basename($this->_dir));
- }
- }
- }
- //读取文件夹所有文件
- private function readDir($dir,&$arr) {
- if ($dirs = opendir($dir)) {
- while (($file=readdir($dirs)) != false) {
- if ($file == '.' || $file == '..') continue;
- $files = $dir .'/'. $file;
- if (is_dir($files) && $this->isEmpty($files)) {
- $this->readDir($files,$arr);
- } else {
- $arr[] = $files;
- }
- }
- }
- closedir($dirs);
- }
- //判断文件夹是否为空
- private function isEmpty($dir) {
- if ($dirs = opendir($dir)) {
- while (($file=readdir($dirs)) != false) {
- if($file != '.' && $file != '..') {
- closedir($dirs);
- return true;
- break;
- }
- }
- closedir($dirs);
- return false;
- }
- }
- }
- ?>
|