ZipFile.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\services\helper;
  10. use fecshop\services\Service;
  11. use Yii;
  12. /**
  13. * Format services.
  14. * @author Terry Zhao <2358269014@qq.com>
  15. * @since 1.0
  16. */
  17. // use \fecshop\services\helper\Format;
  18. class ZipFile extends Service
  19. {
  20. public function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true){
  21. if ($dest_dir) {
  22. $dest_dir .= '/';
  23. }
  24. if ($zip = zip_open($src_file)){
  25. if ($zip){
  26. $splitter = ($create_zip_name_dir === true) ? "." : "/";
  27. if($dest_dir === false){
  28. $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
  29. }
  30. // 如果不存在 创建目标解压目录
  31. $this->create_dirs($dest_dir);
  32. // 对每个文件进行解压
  33. while ($zip_entry = zip_read($zip)){
  34. // 文件不在根目录
  35. $pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
  36. if ($pos_last_slash !== false){
  37. // 创建目录 在末尾带
  38. $this->create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
  39. }
  40. // 打开包
  41. if (zip_entry_open($zip,$zip_entry,"r")){
  42. // 文件名保存在磁盘上
  43. $file_name = $dest_dir.zip_entry_name($zip_entry);
  44. // 检查文件是否需要重写
  45. if ($overwrite === true || $overwrite === false && !is_file($file_name)){
  46. // 读取压缩文件的内容
  47. $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
  48. @file_put_contents($file_name, $fstream);
  49. // 设置权限
  50. chmod($file_name, 0777);
  51. }
  52. // 关闭入口
  53. zip_entry_close($zip_entry);
  54. }
  55. }
  56. // 关闭压缩包
  57. zip_close($zip);
  58. }
  59. }else{
  60. return false;
  61. }
  62. return true;
  63. }
  64. /**
  65. * 创建目录
  66. */
  67. public function create_dirs($path){
  68. if (!is_dir($path)){
  69. $directory_path = "";
  70. $directories = explode("/",$path);
  71. array_pop($directories);
  72. foreach($directories as $directory){
  73. $directory_path .= $directory."/";
  74. if (!is_dir($directory_path)){
  75. mkdir($directory_path);
  76. chmod($directory_path, 0777);
  77. }
  78. }
  79. }
  80. }
  81. }