Unzip.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * function: 解压zip 格式的文件
  4. * author:friker
  5. * date:2015-15-14
  6. * reference:http://php.net/manual/zh/ref.zip.php
  7. * all rights reserved:wujiangwei123@126.com
  8. */
  9. namespace app\common\components;
  10. class Unzip{
  11. public function __construct(){
  12. //init code here...
  13. //header("content-type:text/html;charset=utf8");
  14. }
  15. function transcoding($fileName){
  16. $encoding = mb_detect_encoding($fileName,['UTF-8','GBK','BIG5','CP936']);
  17. if (DIRECTORY_SEPARATOR == '/'){ //linux
  18. $filename = iconv($encoding,'UTF-8',$fileName);
  19. }else{ //win
  20. $filename = iconv($encoding,'GBK',$fileName);
  21. }
  22. return $filename;
  23. }
  24. /**
  25. * 解压文件到指定目录
  26. *
  27. * @param string zip压缩文件的路径
  28. * @param string 解压文件的目的路径
  29. * @param boolean 是否以压缩文件的名字创建目标文件夹
  30. * @param boolean 是否重写已经存在的文件
  31. *
  32. * @return boolean 返回成功 或失败
  33. */
  34. public function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true){
  35. $fileList = array();
  36. $zip = new \ZipArchive;
  37. if ($zip->open($src_file) === TRUE) {
  38. if(!is_dir($dest_dir)) mkdir($dest_dir,0775,true);
  39. $docnum = $zip->numFiles;
  40. for($i = 0; $i < $docnum; $i++) {
  41. $statInfo = $zip->statIndex($i,\ZipArchive::FL_ENC_RAW);
  42. $filename = $this->transcoding($statInfo['name']);
  43. if($statInfo['crc'] == 0) {
  44. //新建目录
  45. if(!is_dir($dest_dir.'/'.substr($filename, 0,-1))) mkdir($dest_dir.'/'.substr($filename, 0,-1),0775,true);
  46. } else {
  47. //拷贝文件
  48. $fileList[] = $dest_dir.'/'.$filename;
  49. @copy('zip://'.$src_file.'#'.$zip->getNameIndex($i), $dest_dir.'/'.$filename);
  50. }
  51. }
  52. $zip->close();
  53. return $fileList;
  54. }else{
  55. return false;
  56. }
  57. }
  58. }
  59. ?>