search
HomeBackend DevelopmentPHP Tutorialphp compressed file help class

  1. /*
  2. File name: /include/zip.php
  3. Author: Horace 2009/04/15
  4. */
  5. class PHPZip{
  6. var $dirInfo = array("0","0");
  7. var $rootDir = '';
  8. var $datasec = array();
  9. var $ctrl_dir = array();
  10. var $eof_ctrl_dir = "/x50/x4b/x05/x06/x00/x00/x00/x00";
  11. var $old_offset = 0;
  12. function downloadZip(){
  13. createZip($dir, $zipfilename, true);
  14. }
  15. function createZip($dir, $zipfilename, $autoDownload = false){
  16. if (@function_exists('gzcompress')){
  17. @set_time_limit("0");
  18. if (is_array($dir)){
  19. $fd = fopen ($dir, "r");
  20. $fileValue = fread ($fd, filesize ($filename));
  21. fclose ($fd);
  22. if (is_array($dir)) $filename = basename($dir);
  23. $this -> addFile($fileValue, "$filename");
  24. }else{
  25. $this->dirTree($dir,$dir);
  26. }
  27. $zipfilenametemp = time().$zipfilename;
  28. $out = $this -> filezip();
  29. $fp = fopen($zipfilenametemp, "w");
  30. fwrite($fp, $out, strlen($out));
  31. fclose($fp);
  32. $filesize = filesize($zipfilenametemp);
  33. if ($filesize if($autoDownload){
  34. header("Content-type: application/octet-stream");
  35. header("Content-disposition: attachment; filename=".$zipfilename);
  36. }
  37. echo $this -> filezip();
  38. }else{
  39. echo "create zip error!";
  40. }
  41. unlink($zipfilenametemp);
  42. }
  43. }
  44. //get dir tree..
  45. function dirTree($directory,$rootDir){
  46. global $_SERVER,$dirInfo,$rootDir;
  47. $fileDir=$rootDir;
  48. $myDir=dir($directory);
  49. while($file=$myDir->read()){
  50. if(is_dir("$directory/$file") and $file!="." and $file!=".."){
  51. $dirInfo[0]++;
  52. $rootDir ="$fileDir$file/";
  53. $this -> addFile('', "$rootDir");
  54. //go on n's folders
  55. $this->dirTree("$directory/$file",$rootDir);
  56. }else{
  57. if($file!="." and $file!=".."){
  58. $dirInfo[1]++;
  59. //$fd = fopen ("$directory/$file", "r");
  60. $fileValue = file_get_contents("$directory/$file");
  61. //fclose ($fd);
  62. $this -> addFile($fileValue, "$fileDir$file");
  63. }
  64. }
  65. }
  66. $myDir->close();
  67. }
  68. function unix2DosTime($unixtime = 0) {
  69. $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
  70. if ($timearray['year'] $timearray['year'] = 1980;
  71. $timearray['mon'] = 1;
  72. $timearray['mday'] = 1;
  73. $timearray['hours'] = 0;
  74. $timearray['minutes'] = 0;
  75. $timearray['seconds'] = 0;
  76. } // end if
  77. return (($timearray['year'] - 1980) ($timearray['hours'] > 1);
  78. }
  79. function addFile($data, $name, $time = 0){
  80. $name = str_replace('//', '/', $name);
  81. $dtime = dechex($this->unix2DosTime($time));
  82. $hexdtime = '/x' . $dtime[6] . $dtime[7]
  83. . '/x' . $dtime[4] . $dtime[5]
  84. . '/x' . $dtime[2] . $dtime[3]
  85. . '/x' . $dtime[0] . $dtime[1];
  86. eval('$hexdtime = "' . $hexdtime . '";');
  87. $fr = "/x50/x4b/x03/x04";
  88. $fr .= "/x14/x00"; // ver needed to extract
  89. $fr .= "/x00/x00"; // gen purpose bit flag
  90. $fr .= "/x08/x00"; // compression method
  91. $fr .= $hexdtime; // last mod time and date
  92. // "local file header" segment
  93. $unc_len = strlen($data);
  94. $crc = crc32($data);
  95. $zdata = gzcompress($data);
  96. $c_len = strlen($zdata);
  97. $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
  98. $fr .= pack('V', $crc); // crc32
  99. $fr .= pack('V', $c_len); // compressed filesize
  100. $fr .= pack('V', $unc_len); // uncompressed filesize
  101. $fr .= pack('v', strlen($name)); // length of filename
  102. $fr .= pack('v', 0); // extra field length
  103. $fr .= $name;
  104. // "file data" segment
  105. $fr .= $zdata;
  106. // "data descriptor" segment (optional but necessary if archive is not
  107. // served as file)
  108. $fr .= pack('V', $crc); // crc32
  109. $fr .= pack('V', $c_len); // compressed filesize
  110. $fr .= pack('V', $unc_len); // uncompressed filesize
  111. // add this entry to array
  112. $this -> datasec[] = $fr;
  113. $new_offset = strlen(implode('', $this->datasec));
  114. // now add to central directory record
  115. $cdrec = "/x50/x4b/x01/x02";
  116. $cdrec .= "/x00/x00"; // version made by
  117. $cdrec .= "/x14/x00"; // version needed to extract
  118. $cdrec .= "/x00/x00"; // gen purpose bit flag
  119. $cdrec .= "/x08/x00"; // compression method
  120. $cdrec .= $hexdtime; // last mod time & date
  121. $cdrec .= pack('V', $crc); // crc32
  122. $cdrec .= pack('V', $c_len); // compressed filesize
  123. $cdrec .= pack('V', $unc_len); // uncompressed filesize
  124. $cdrec .= pack('v', strlen($name) ); // length of filename
  125. $cdrec .= pack('v', 0 ); // extra field length
  126. $cdrec .= pack('v', 0 ); // file comment length
  127. $cdrec .= pack('v', 0 ); // disk number start
  128. $cdrec .= pack('v', 0 ); // internal file attributes
  129. $cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set
  130. $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
  131. $this -> old_offset = $new_offset;
  132. $cdrec .= $name;
  133. // optional extra field, file comment goes here
  134. // save to central directory
  135. $this -> ctrl_dir[] = $cdrec;
  136. }
  137. function filezip(){
  138. $data = implode('', $this -> datasec);
  139. $ctrldir = implode('', $this -> ctrl_dir);
  140. return
  141. $data .
  142. $ctrldir .
  143. $this -> eof_ctrl_dir .
  144. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
  145. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
  146. pack('V', strlen($ctrldir)) . // size of central dir
  147. pack('V', strlen($data)) . // offset to start of central dir
  148. "/x00/x00"; // .zip file comment length
  149. }
  150. }
  151. ?>
  152. 还有另外一个比较简单的
  153. [php] view plaincopy
  154. class createzip
  155. {
  156. /* @creates a compressed zip file 将多个文件压缩成一个zip文件的函数
  157. * @$files 数组类型 实例array("1.jpg","2.jpg");
  158. * @destination 目标文件的路径 如"c:/androidyue.zip"
  159. * @$overwrite 是否为覆盖与目标文件相同的文件
  160. * @Recorded By Androidyue
  161. * @Blog:http://thinkblog.sinaapp.com
  162. */
  163. function create_zip($files = array(),$destination = '',$overwrite = false)
  164. {
  165. //如果zip文件已经存在并且设置为不重写返回false
  166. if(file_exists($destination) && !$overwrite) { return false; }
  167. $valid_files = array();
  168. //if files were passed in...
  169. //Get the real and valid file name
  170. if(is_array($files)) {
  171. //cycle through each file
  172. foreach($ files as $file) {
  173. //make sure the file exists
  174. if(file_exists($file)) {
  175. $valid_files[] = $file;
  176. }
  177. }
  178. }
  179. //If a real and valid file exists
  180. if (count($valid_files))
  181. {
  182. //create the archive
  183. $zip = new ZipArchive();
  184. //Open the file if it already exists, overwrite it, if not, create it
  185. if($zip->open( $destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  186. return false;
  187. }
  188. //Add files to the compressed file
  189. foreach($valid_files as $file) {
  190. $zip ->addFile($file,$file);
  191. }
  192. //Close the file
  193. $zip->close();
  194. //Check whether the file exists
  195. return file_exists($destination);
  196. }
  197. else{
  198. //If there is no real and valid file, return false
  199. return false;
  200. }
  201. }
  202. }
  203. /****
  204. //Test function
  205. $files=array('temp.php','test.php');
  206. create_zip($files, 'myzipfile.zip', true);
  207. ****/
  208. ?>
Copy code

Compressed file, php


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool