Home Backend Development PHP Tutorial PHP packages a set of files into a zip package.

PHP packages a set of files into a zip package.

Jul 25, 2016 am 08:56 AM

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


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,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

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.

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.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles