PHPZip.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. namespace util;
  3. /**
  4. * 文件压缩解压类
  5. */
  6. class PHPZip {
  7. private $ctrl_dir = array();
  8. private $datasec = array();
  9. /**********************************************************
  10. * 压缩部分
  11. **********************************************************/
  12. // ------------------------------------------------------ //
  13. // #遍历指定文件夹
  14. //
  15. // $archive = new PHPZip();
  16. // $filelist = $archive->visitFile(文件夹路径);
  17. // print "当前文件夹的文件:<p>\r\n";
  18. // foreach($filelist as $file)
  19. // printf("%s<br>\r\n", $file);
  20. // ------------------------------------------------------ //
  21. var $fileList = array();
  22. public function visitFile($path)
  23. {
  24. global $fileList;
  25. $path = str_replace("\\", "/", $path);
  26. $fdir = dir($path);
  27. while(($file = $fdir->read()) !== false)
  28. {
  29. if($file == '.' || $file == '..'){ continue; }
  30. $pathSub = preg_replace("*/{2,}*", "/", $path."/".$file); // 替换多个反斜杠
  31. $fileList[] = is_dir($pathSub) ? $pathSub."/" : $pathSub;
  32. if(is_dir($pathSub)){ $this->visitFile($pathSub); }
  33. }
  34. $fdir->close();
  35. return $fileList;
  36. }
  37. private function unix2DosTime($unixtime = 0)
  38. {
  39. $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
  40. if($timearray['year'] < 1980)
  41. {
  42. $timearray['year'] = 1980;
  43. $timearray['mon'] = 1;
  44. $timearray['mday'] = 1;
  45. $timearray['hours'] = 0;
  46. $timearray['minutes'] = 0;
  47. $timearray['seconds'] = 0;
  48. }
  49. return ( ($timearray['year'] - 1980) << 25)
  50. | ($timearray['mon'] << 21)
  51. | ($timearray['mday'] << 16)
  52. | ($timearray['hours'] << 11)
  53. | ($timearray['minutes'] << 5)
  54. | ($timearray['seconds'] >> 1);
  55. }
  56. var $old_offset = 0;
  57. private function addFile($data, $filename, $time = 0)
  58. {
  59. $filename = str_replace('\\', '/', $filename);
  60. $dtime = dechex($this->unix2DosTime($time));
  61. $hexdtime = '\x' . $dtime[6] . $dtime[7]
  62. . '\x' . $dtime[4] . $dtime[5]
  63. . '\x' . $dtime[2] . $dtime[3]
  64. . '\x' . $dtime[0] . $dtime[1];
  65. eval('$hexdtime = "' . $hexdtime . '";');
  66. $fr = "\x50\x4b\x03\x04";
  67. $fr .= "\x14\x00";
  68. $fr .= "\x00\x00";
  69. $fr .= "\x08\x00";
  70. $fr .= $hexdtime;
  71. $unc_len = strlen($data);
  72. $crc = crc32($data);
  73. $zdata = gzcompress($data);
  74. $c_len = strlen($zdata);
  75. $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
  76. $fr .= pack('V', $crc);
  77. $fr .= pack('V', $c_len);
  78. $fr .= pack('V', $unc_len);
  79. $fr .= pack('v', strlen($filename));
  80. $fr .= pack('v', 0);
  81. $fr .= $filename;
  82. $fr .= $zdata;
  83. $fr .= pack('V', $crc);
  84. $fr .= pack('V', $c_len);
  85. $fr .= pack('V', $unc_len);
  86. $this->datasec[] = $fr;
  87. $new_offset = strlen(implode('', $this->datasec));
  88. $cdrec = "\x50\x4b\x01\x02";
  89. $cdrec .= "\x00\x00";
  90. $cdrec .= "\x14\x00";
  91. $cdrec .= "\x00\x00";
  92. $cdrec .= "\x08\x00";
  93. $cdrec .= $hexdtime;
  94. $cdrec .= pack('V', $crc);
  95. $cdrec .= pack('V', $c_len);
  96. $cdrec .= pack('V', $unc_len);
  97. $cdrec .= pack('v', strlen($filename) );
  98. $cdrec .= pack('v', 0 );
  99. $cdrec .= pack('v', 0 );
  100. $cdrec .= pack('v', 0 );
  101. $cdrec .= pack('v', 0 );
  102. $cdrec .= pack('V', 32 );
  103. $cdrec .= pack('V', $this->old_offset );
  104. $this->old_offset = $new_offset;
  105. $cdrec .= $filename;
  106. $this->ctrl_dir[] = $cdrec;
  107. }
  108. var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
  109. private function file()
  110. {
  111. $data = implode('', $this->datasec);
  112. $ctrldir = implode('', $this->ctrl_dir);
  113. return $data
  114. . $ctrldir
  115. . $this->eof_ctrl_dir
  116. . pack('v', sizeof($this->ctrl_dir))
  117. . pack('v', sizeof($this->ctrl_dir))
  118. . pack('V', strlen($ctrldir))
  119. . pack('V', strlen($data))
  120. . "\x00\x00";
  121. }
  122. // ------------------------------------------------------ //
  123. // #压缩到服务器
  124. //
  125. // $archive = new PHPZip();
  126. // $archive->Zip("需压缩的文件所在目录", "ZIP压缩文件名");
  127. // ------------------------------------------------------ //
  128. public function Zip($dir, $saveName)
  129. {
  130. if(@!function_exists('gzcompress')){ return; }
  131. ob_end_clean();
  132. $filelist = $this->visitFile($dir);
  133. if(count($filelist) == 0){ return; }
  134. foreach($filelist as $file)
  135. {
  136. if(!file_exists($file) || !is_file($file)){ continue; }
  137. $fd = fopen($file, "rb");
  138. $content = @fread($fd, filesize($file));
  139. fclose($fd);
  140. // 1.删除$dir的字符(./folder/file.txt删除./folder/)
  141. // 2.如果存在/就删除(/file.txt删除/)
  142. $file = substr($file, strlen($dir));
  143. if(substr($file, 0, 1) == "\\" || substr($file, 0, 1) == "/"){ $file = substr($file, 1); }
  144. $this->addFile($content, $file);
  145. }
  146. $out = $this->file();
  147. $fp = fopen($saveName, "wb");
  148. fwrite($fp, $out, strlen($out));
  149. fclose($fp);
  150. }
  151. // ------------------------------------------------------ //
  152. // #压缩并直接下载
  153. //
  154. // $archive = new PHPZip();
  155. // $archive->ZipAndDownload("需压缩的文件所在目录");
  156. // ------------------------------------------------------ //
  157. public function ZipAndDownload($dir, $file_name = '')
  158. {
  159. if(@!function_exists('gzcompress')){ return; }
  160. ob_end_clean();
  161. $filelist = $this->visitFile($dir);
  162. if(count($filelist) == 0){ return; }
  163. foreach($filelist as $file)
  164. {
  165. if(!file_exists($file) || !is_file($file)){ continue; }
  166. $fd = fopen($file, "rb");
  167. $content = @fread($fd, filesize($file));
  168. fclose($fd);
  169. // 1.删除$dir的字符(./folder/file.txt删除./folder/)
  170. // 2.如果存在/就删除(/file.txt删除/)
  171. $file = substr($file, strlen($dir));
  172. if(substr($file, 0, 1) == "\\" || substr($file, 0, 1) == "/"){ $file = substr($file, 1); }
  173. $this->addFile($content, $file);
  174. }
  175. $out = $this->file();
  176. $file_name = $file_name == '' ? 'file_'.date("YmdHis", time()) : $file_name;
  177. @header('Content-Encoding: none');
  178. @header('Content-Type: application/zip');
  179. @header('Content-Disposition: attachment ; filename='.$file_name.'.zip');
  180. @header('Pragma: no-cache');
  181. @header('Expires: 0');
  182. print($out);
  183. }
  184. /**********************************************************
  185. * 解压部分
  186. **********************************************************/
  187. // ------------------------------------------------------ //
  188. // ReadCentralDir($zip, $zipfile)
  189. // $zip是经过@fopen($zipfile, 'rb')打开的
  190. // $zipfile是zip文件的路径
  191. // ------------------------------------------------------ //
  192. private function ReadCentralDir($zip, $zipfile)
  193. {
  194. $size = filesize($zipfile);
  195. $max_size = ($size < 277) ? $size : 277;
  196. @fseek($zip, $size - $max_size);
  197. $pos = ftell($zip);
  198. $bytes = 0x00000000;
  199. while($pos < $size)
  200. {
  201. $byte = @fread($zip, 1);
  202. $bytes = ($bytes << 8) | Ord($byte);
  203. $pos++;
  204. if($bytes == 0x504b0506){ break; }
  205. }
  206. $data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', fread($zip, 18));
  207. $centd['comment'] = ($data['comment_size'] != 0) ? fread($zip, $data['comment_size']) : ''; // 注释
  208. $centd['entries'] = $data['entries'];
  209. $centd['disk_entries'] = $data['disk_entries'];
  210. $centd['offset'] = $data['offset'];
  211. $centd['disk_start'] = $data['disk_start'];
  212. $centd['size'] = $data['size'];
  213. $centd['disk'] = $data['disk'];
  214. return $centd;
  215. }
  216. private function ReadCentralFileHeaders($zip)
  217. {
  218. $binary_data = fread($zip, 46);
  219. $header = unpack('vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $binary_data);
  220. $header['filename'] = ($header['filename_len'] != 0) ? fread($zip, $header['filename_len']) : '';
  221. $header['extra'] = ($header['extra_len'] != 0) ? fread($zip, $header['extra_len']) : '';
  222. $header['comment'] = ($header['comment_len'] != 0) ? fread($zip, $header['comment_len']) : '';
  223. if($header['mdate'] && $header['mtime'])
  224. {
  225. $hour = ($header['mtime'] & 0xF800) >> 11;
  226. $minute = ($header['mtime'] & 0x07E0) >> 5;
  227. $seconde = ($header['mtime'] & 0x001F) * 2;
  228. $year = (($header['mdate'] & 0xFE00) >> 9) + 1980;
  229. $month = ($header['mdate'] & 0x01E0) >> 5;
  230. $day = $header['mdate'] & 0x001F;
  231. $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
  232. } else {
  233. $header['mtime'] = time();
  234. }
  235. $header['stored_filename'] = $header['filename'];
  236. $header['status'] = 'ok';
  237. if(substr($header['filename'], -1) == '/'){ $header['external'] = 0x41FF0010; } // 判断是否文件夹
  238. return $header;
  239. }
  240. private function ReadFileHeader($zip)
  241. {
  242. $binary_data = fread($zip, 30);
  243. $data = unpack('vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $binary_data);
  244. $header['filename'] = fread($zip, $data['filename_len']);
  245. $header['extra'] = ($data['extra_len'] != 0) ? fread($zip, $data['extra_len']) : '';
  246. $header['compression'] = $data['compression'];
  247. $header['size'] = $data['size'];
  248. $header['compressed_size'] = $data['compressed_size'];
  249. $header['crc'] = $data['crc'];
  250. $header['flag'] = $data['flag'];
  251. $header['mdate'] = $data['mdate'];
  252. $header['mtime'] = $data['mtime'];
  253. if($header['mdate'] && $header['mtime']){
  254. $hour = ($header['mtime'] & 0xF800) >> 11;
  255. $minute = ($header['mtime'] & 0x07E0) >> 5;
  256. $seconde = ($header['mtime'] & 0x001F) * 2;
  257. $year = (($header['mdate'] & 0xFE00) >> 9) + 1980;
  258. $month = ($header['mdate'] & 0x01E0) >> 5;
  259. $day = $header['mdate'] & 0x001F;
  260. $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
  261. }else{
  262. $header['mtime'] = time();
  263. }
  264. $header['stored_filename'] = $header['filename'];
  265. $header['status'] = "ok";
  266. return $header;
  267. }
  268. private function ExtractFile($header, $to, $zip)
  269. {
  270. $header = $this->readfileheader($zip);
  271. if(substr($to, -1) != "/"){ $to .= "/"; }
  272. if(!@is_dir($to)){ @mkdir($to, 0777); }
  273. $pth = explode("/", dirname($header['filename']));
  274. for($i=0; isset($pth[$i]); $i++){
  275. if(!$pth[$i]){ continue; }
  276. $pthss .= $pth[$i]."/";
  277. if(!is_dir($to.$pthss)){ @mkdir($to.$pthss, 0777); }
  278. }
  279. if(!($header['external'] == 0x41FF0010) && !($header['external'] == 16))
  280. {
  281. if($header['compression'] == 0)
  282. {
  283. $fp = @fopen($to.$header['filename'], 'wb');
  284. if(!$fp){ return(-1); }
  285. $size = $header['compressed_size'];
  286. while($size != 0)
  287. {
  288. $read_size = ($size < 2048 ? $size : 2048);
  289. $buffer = fread($zip, $read_size);
  290. $binary_data = pack('a'.$read_size, $buffer);
  291. @fwrite($fp, $binary_data, $read_size);
  292. $size -= $read_size;
  293. }
  294. fclose($fp);
  295. touch($to.$header['filename'], $header['mtime']);
  296. }else{
  297. $fp = @fopen($to.$header['filename'].'.gz', 'wb');
  298. if(!$fp){ return(-1); }
  299. $binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($header['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
  300. fwrite($fp, $binary_data, 10);
  301. $size = $header['compressed_size'];
  302. while($size != 0)
  303. {
  304. $read_size = ($size < 1024 ? $size : 1024);
  305. $buffer = fread($zip, $read_size);
  306. $binary_data = pack('a'.$read_size, $buffer);
  307. @fwrite($fp, $binary_data, $read_size);
  308. $size -= $read_size;
  309. }
  310. $binary_data = pack('VV', $header['crc'], $header['size']);
  311. fwrite($fp, $binary_data, 8);
  312. fclose($fp);
  313. $gzp = @gzopen($to.$header['filename'].'.gz', 'rb') or die("Cette archive est compress!");
  314. if(!$gzp){ return(-2); }
  315. $fp = @fopen($to.$header['filename'], 'wb');
  316. if(!$fp){ return(-1); }
  317. $size = $header['size'];
  318. while($size != 0)
  319. {
  320. $read_size = ($size < 2048 ? $size : 2048);
  321. $buffer = gzread($gzp, $read_size);
  322. $binary_data = pack('a'.$read_size, $buffer);
  323. @fwrite($fp, $binary_data, $read_size);
  324. $size -= $read_size;
  325. }
  326. fclose($fp); gzclose($gzp);
  327. touch($to.$header['filename'], $header['mtime']);
  328. @unlink($to.$header['filename'].'.gz');
  329. }
  330. }
  331. return true;
  332. }
  333. // ------------------------------------------------------ //
  334. // #解压文件
  335. //
  336. // $archive = new PHPZip();
  337. // $zipfile = "ZIP压缩文件名";
  338. // $savepath = "解压缩目录名";
  339. // $zipfile = $unzipfile;
  340. // $savepath = $unziptarget;
  341. // $array = $archive->GetZipInnerFilesInfo($zipfile);
  342. // $filecount = 0;
  343. // $dircount = 0;
  344. // $failfiles = array();
  345. // set_time_limit(0); // 修改为不限制超时时间(默认为30秒)
  346. //
  347. // for($i=0; $i<count($array); $i++) {
  348. // if($array[$i][folder] == 0){
  349. // if($archive->unZip($zipfile, $savepath, $i) > 0){
  350. // $filecount++;
  351. // }else{
  352. // $failfiles[] = $array[$i][filename];
  353. // }
  354. // }else{
  355. // $dircount++;
  356. // }
  357. // }
  358. // set_time_limit(30);
  359. //printf("文件夹:%d&nbsp;&nbsp;&nbsp;&nbsp;解压文件:%d&nbsp;&nbsp;&nbsp;&nbsp;失败:%d<br>\r\n", $dircount, $filecount, count($failfiles));
  360. //if(count($failfiles) > 0){
  361. // foreach($failfiles as $file){
  362. // printf("&middot;%s<br>\r\n", $file);
  363. // }
  364. //}
  365. // ------------------------------------------------------ //
  366. public function unZip($zipfile, $to, $index = Array(-1))
  367. {
  368. $ok = 0;
  369. $zip = @fopen($zipfile, 'rb');
  370. if(!$zip){ return(-1); }
  371. $cdir = $this->ReadCentralDir($zip, $zipfile);
  372. $pos_entry = $cdir['offset'];
  373. if(!is_array($index)){ $index = array($index); }
  374. for($i=0; $index[$i]; $i++)
  375. {
  376. if(intval($index[$i]) != $index[$i] || $index[$i] > $cdir['entries'])
  377. {
  378. return(-1);
  379. }
  380. }
  381. for($i=0; $i<$cdir['entries']; $i++)
  382. {
  383. @fseek($zip, $pos_entry);
  384. $header = $this->ReadCentralFileHeaders($zip);
  385. $header['index'] = $i;
  386. $pos_entry = ftell($zip);
  387. @rewind($zip);
  388. fseek($zip, $header['offset']);
  389. if(in_array("-1", $index) || in_array($i, $index))
  390. {
  391. $stat[$header['filename']] = $this->ExtractFile($header, $to, $zip);
  392. }
  393. }
  394. fclose($zip);
  395. return $stat;
  396. }
  397. /**********************************************************
  398. * 其它部分
  399. **********************************************************/
  400. // ------------------------------------------------------ //
  401. // #获取被压缩文件的信息
  402. //
  403. // $archive = new PHPZip();
  404. // $array = $archive->GetZipInnerFilesInfo(ZIP压缩文件名);
  405. // for($i=0; $i<count($array); $i++) {
  406. // printf("<b>&middot;%s</b><br>\r\n", $array[$i][filename]);
  407. // foreach($array[$i] as $key => $value)
  408. // printf("%s => %s<br>\r\n", $key, $value);
  409. // print "\r\n<p>------------------------------------<p>\r\n\r\n";
  410. // }
  411. // ------------------------------------------------------ //
  412. public function GetZipInnerFilesInfo($zipfile)
  413. {
  414. $zip = @fopen($zipfile, 'rb');
  415. if(!$zip){ return(0); }
  416. $centd = $this->ReadCentralDir($zip, $zipfile);
  417. @rewind($zip);
  418. @fseek($zip, $centd['offset']);
  419. $ret = array();
  420. for($i=0; $i<$centd['entries']; $i++)
  421. {
  422. $header = $this->ReadCentralFileHeaders($zip);
  423. $header['index'] = $i;
  424. $info = array(
  425. 'filename' => $header['filename'], // 文件名
  426. 'stored_filename' => $header['stored_filename'], // 压缩后文件名
  427. 'size' => $header['size'], // 大小
  428. 'compressed_size' => $header['compressed_size'], // 压缩后大小
  429. 'crc' => strtoupper(dechex($header['crc'])), // CRC32
  430. 'mtime' => date("Y-m-d H:i:s",$header['mtime']), // 文件修改时间
  431. 'comment' => $header['comment'], // 注释
  432. 'folder' => ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0, // 是否为文件夹
  433. 'index' => $header['index'], // 文件索引
  434. 'status' => $header['status'] // 状态
  435. );
  436. $ret[] = $info;
  437. unset($header);
  438. }
  439. fclose($zip);
  440. return $ret;
  441. }
  442. // ------------------------------------------------------ //
  443. // #获取压缩文件的注释
  444. //
  445. // $archive = new PHPZip();
  446. // echo $archive->GetZipComment(ZIP压缩文件名);
  447. // ------------------------------------------------------ //
  448. public function GetZipComment($zipfile)
  449. {
  450. $zip = @fopen($zipfile, 'rb');
  451. if(!$zip){ return(0); }
  452. $centd = $this->ReadCentralDir($zip, $zipfile);
  453. fclose($zip);
  454. return $centd[comment];
  455. }
  456. }