Dozip.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace app\common\components;
  3. use Yii;
  4. /*
  5. * $res = new MakeZip($dir,$zipName);
  6. *@ $dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt'
  7. *@ $zipName是压缩后的压缩包名称,可使用路径,例 'a/test.zip'或者'test.zip'
  8. **/
  9. class Dozip {
  10. private $_dir;
  11. private $_zipDir;
  12. private $_zipName;
  13. public function __construct($dir,$zipName) {
  14. $this->_dir = $dir;
  15. $this->_zipDir = basename($dir);
  16. $this->_zipName = $zipName;
  17. $this->mkdirs();
  18. $this->creat();
  19. }
  20. //检测并生成目录
  21. private function mkdirs() {
  22. if (!is_dir(dirname($this->_zipName))) {
  23. $arr = explode('/', dirname($this->_zipName));
  24. $arrs = '';
  25. foreach($arr as $value) {
  26. if (!is_dir($arrs.$value)) {
  27. if (!!mkdir($arrs.$value)) {
  28. $arrs .= $value.'/';
  29. }
  30. }
  31. }
  32. }
  33. }
  34. //生成Zip压缩包
  35. private function creat() {
  36. $zip = new \ZipArchive;
  37. if (is_dir($this->_dir)) {
  38. $this->readDir($this->_dir,$files);
  39. if ($zip->open($this->_zipName,\ZipArchive::OVERWRITE|\ZipArchive::CREATE)) {
  40. foreach ($files as $value) {
  41. preg_match('/\/('.$this->_zipDir.'\/.*)/', $value, $match);
  42. if (is_dir($value)) {
  43. $zip->addEmptyDir($value, $match[1]);
  44. } else {
  45. $zip->addFile($value, $match[1]);
  46. $zip->renameName($value,$this->_zipDir);
  47. }
  48. }
  49. $zip->close();
  50. }
  51. } else {
  52. if ($zip->open($this->_zipName,\ZipArchive::OVERWRITE|\ZipArchive::CREATE)) {
  53. $zip->addFile($this->_dir, basename($this->_dir));
  54. }
  55. }
  56. }
  57. //读取文件夹所有文件
  58. private function readDir($dir,&$arr) {
  59. if ($dirs = opendir($dir)) {
  60. while (($file=readdir($dirs)) != false) {
  61. if ($file == '.' || $file == '..') continue;
  62. $files = $dir .'/'. $file;
  63. if (is_dir($files) && $this->isEmpty($files)) {
  64. $this->readDir($files,$arr);
  65. } else {
  66. $arr[] = $files;
  67. }
  68. }
  69. }
  70. closedir($dirs);
  71. }
  72. //判断文件夹是否为空
  73. private function isEmpty($dir) {
  74. if ($dirs = opendir($dir)) {
  75. while (($file=readdir($dirs)) != false) {
  76. if($file != '.' && $file != '..') {
  77. closedir($dirs);
  78. return true;
  79. break;
  80. }
  81. }
  82. closedir($dirs);
  83. return false;
  84. }
  85. }
  86. }
  87. ?>