Home Backend Development PHP Tutorial A php class that packages a set of files into a zip

A php class that packages a set of files into a zip

Jul 25, 2016 am 08:43 AM

This php class can add files to the array one by one, and finally package the added files into zip

  1. /* $Id: zip.lib.php,v 1.1 2004/02/14 15:21:18 anoncvs_tusedb Exp $ */
  2. // vim: expandtab sw=4 ts=4 sts=4:
  3. /**
  4. * Zip file creation class.
  5. * Makes zip files.
  6. *
  7. * Last Modification and Extension By :
  8. *
  9. * Hasin Hayder
  10. * HomePage : www.hasinme.info
  11. * Email : countdraculla@gmail.com
  12. * IDE : PHP Designer 2005
  13. *
  14. *
  15. * Originally Based on :
  16. *
  17. * http://www.zend.com/codex.php?id=535&single=1
  18. * By Eric Mueller
  19. *
  20. * http://www.zend.com/codex.php?id=470&single=1
  21. * by Denis125
  22. *
  23. * a patch from Peter Listiak for last modified
  24. * date and time of the compressed file
  25. *
  26. * Official ZIP file format: http://www.pkware.com/appnote.txt
  27. *
  28. * @access public
  29. */
  30. class zipfile
  31. {
  32. /**
  33. * Array to store compressed data
  34. *
  35. * @public array $datasec
  36. */
  37. public $datasec = array();
  38. /**
  39. * Central directory
  40. *
  41. * @public array $ctrl_dir
  42. */
  43. public $ctrl_dir = array();
  44. /**
  45. * End of central directory record
  46. *
  47. * @public string $eof_ctrl_dir
  48. */
  49. public $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
  50. /**
  51. * Last offset position
  52. *
  53. * @public integer $old_offset
  54. */
  55. public $old_offset = 0;
  56. /**
  57. * Converts an Unix timestamp to a four byte DOS date and time format (date
  58. * in high two bytes, time in low two bytes allowing magnitude comparison).
  59. *
  60. * @param integer the current Unix timestamp
  61. *
  62. * @return integer the current date in a four byte DOS format
  63. *
  64. * @access private
  65. */
  66. function unix2DosTime($unixtime = 0) {
  67. $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
  68. if ($timearray['year'] < 1980) {
  69. $timearray['year'] = 1980;
  70. $timearray['mon'] = 1;
  71. $timearray['mday'] = 1;
  72. $timearray['hours'] = 0;
  73. $timearray['minutes'] = 0;
  74. $timearray['seconds'] = 0;
  75. } // end if
  76. return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
  77. ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
  78. }// end of the 'unix2DosTime()' method
  79. /**
  80. * Adds "file" to archive
  81. *
  82. * @param string file contents
  83. * @param string name of the file in the archive (may contains the path)
  84. * @param integer the current timestamp
  85. *
  86. * @access public
  87. */
  88. function addFile($data, $name, $time = 0)
  89. {
  90. $name = str_replace('\', '/', $name);
  91. $dtime = dechex($this->unix2DosTime($time));
  92. $hexdtime = 'x' . $dtime[6] . $dtime[7]
  93. . 'x' . $dtime[4] . $dtime[5]
  94. . 'x' . $dtime[2] . $dtime[3]
  95. . 'x' . $dtime[0] . $dtime[1];
  96. eval('$hexdtime = "' . $hexdtime . '";');
  97. $fr = "x50x4bx03x04";
  98. $fr .= "x14x00"; // ver needed to extract
  99. $fr .= "x00x00"; // gen purpose bit flag
  100. $fr .= "x08x00"; // compression method
  101. $fr .= $hexdtime; // last mod time and date
  102. // "local file header" segment
  103. $unc_len = strlen($data);
  104. $crc = crc32($data);
  105. $zdata = gzcompress($data);
  106. $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
  107. $c_len = strlen($zdata);
  108. $fr .= pack('V', $crc); // crc32
  109. $fr .= pack('V', $c_len); // compressed filesize
  110. $fr .= pack('V', $unc_len); // uncompressed filesize
  111. $fr .= pack('v', strlen($name)); // length of filename
  112. $fr .= pack('v', 0); // extra field length
  113. $fr .= $name;
  114. // "file data" segment
  115. $fr .= $zdata;
  116. // "data descriptor" segment (optional but necessary if archive is not
  117. // served as file)
  118. $fr .= pack('V', $crc); // crc32
  119. $fr .= pack('V', $c_len); // compressed filesize
  120. $fr .= pack('V', $unc_len); // uncompressed filesize
  121. // add this entry to array
  122. $this -> datasec[] = $fr;
  123. // now add to central directory record
  124. $cdrec = "x50x4bx01x02";
  125. $cdrec .= "x00x00"; // version made by
  126. $cdrec .= "x14x00"; // version needed to extract
  127. $cdrec .= "x00x00"; // gen purpose bit flag
  128. $cdrec .= "x08x00"; // compression method
  129. $cdrec .= $hexdtime; // last mod time & date
  130. $cdrec .= pack('V', $crc); // crc32
  131. $cdrec .= pack('V', $c_len); // compressed filesize
  132. $cdrec .= pack('V', $unc_len); // uncompressed filesize
  133. $cdrec .= pack('v', strlen($name) ); // length of filename
  134. $cdrec .= pack('v', 0 ); // extra field length
  135. $cdrec .= pack('v', 0 ); // file comment length
  136. $cdrec .= pack('v', 0 ); // disk number start
  137. $cdrec .= pack('v', 0 ); // internal file attributes
  138. $cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set
  139. $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
  140. $this -> old_offset += strlen($fr);
  141. $cdrec .= $name;
  142. // optional extra field, file comment goes here
  143. // save to central directory
  144. $this -> ctrl_dir[] = $cdrec;
  145. } // end of the 'addFile()' method
  146. /**
  147. * Dumps out file
  148. *
  149. * @return string the zipped file
  150. *
  151. * @access public
  152. */
  153. function file()
  154. {
  155. $data = implode('', $this -> datasec);
  156. $ctrldir = implode('', $this -> ctrl_dir);
  157. return
  158. $data .
  159. $ctrldir .
  160. $this -> eof_ctrl_dir .
  161. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
  162. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
  163. pack('V', strlen($ctrldir)) . // size of central dir
  164. pack('V', strlen($data)) . // offset to start of central dir
  165. "x00x00"; // .zip file comment length
  166. }// end of the 'file()' method
  167. /**
  168. * A Wrapper of original addFile Function
  169. *
  170. * Created By Hasin Hayder at 29th Jan, 1:29 AM
  171. *
  172. * @param array An Array of files with relative/absolute path to be added in Zip File
  173. *
  174. * @access public
  175. */
  176. function addFiles($files /*Only Pass Array*/)
  177. {
  178. foreach($files as $file)
  179. {
  180. if (is_file($file)) //directory check
  181. {
  182. $data = implode("",file($file));
  183. $this->addFile($data,$file);
  184. }
  185. }
  186. }
  187. /**
  188. * A Wrapper of original file Function
  189. *
  190. * Created By Hasin Hayder at 29th Jan, 1:29 AM
  191. *
  192. * @param string Output file name
  193. *
  194. * @access public
  195. */
  196. function output($file)
  197. {
  198. $fp=fopen($file,"w");
  199. fwrite($fp,$this->file());
  200. fclose($fp);
  201. }
  202. } // end of the 'zipfile' class
复制代码

php, zip


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles