search
HomeBackend DevelopmentPHP TutorialA php class that packages a set of files into a zip

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'] $timearray['year'] = 1980;
  69. $timearray['mon'] = 1;
  70. $timearray['mday'] = 1;
  71. $timearray['hours'] = 0;
  72. $timearray['minutes'] = 0;
  73. $timearray['seconds'] = 0;
  74. } // end if
  75. return (($timearray['year'] - 1980) ($timearray['hours'] > 1);
  76. }// end of the 'unix2DosTime()' method
  77. /**
  78. * Adds "file" to archive
  79. *
  80. * @param string file contents
  81. * @param string name of the file in the archive (may contains the path)
  82. * @param integer the current timestamp
  83. *
  84. * @access public
  85. */
  86. function addFile($data, $name, $time = 0)
  87. {
  88. $name = str_replace('\', '/', $name);
  89. $dtime = dechex($this->unix2DosTime($time));
  90. $hexdtime = 'x' . $dtime[6] . $dtime[7]
  91. . 'x' . $dtime[4] . $dtime[5]
  92. . 'x' . $dtime[2] . $dtime[3]
  93. . 'x' . $dtime[0] . $dtime[1];
  94. eval('$hexdtime = "' . $hexdtime . '";');
  95. $fr = "x50x4bx03x04";
  96. $fr .= "x14x00"; // ver needed to extract
  97. $fr .= "x00x00"; // gen purpose bit flag
  98. $fr .= "x08x00"; // compression method
  99. $fr .= $hexdtime; // last mod time and date
  100. // "local file header" segment
  101. $unc_len = strlen($data);
  102. $crc = crc32($data);
  103. $zdata = gzcompress($data);
  104. $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
  105. $c_len = strlen($zdata);
  106. $fr .= pack('V', $crc); // crc32
  107. $fr .= pack('V', $c_len); // compressed filesize
  108. $fr .= pack('V', $unc_len); // uncompressed filesize
  109. $fr .= pack('v', strlen($name)); // length of filename
  110. $fr .= pack('v', 0); // extra field length
  111. $fr .= $name;
  112. // "file data" segment
  113. $fr .= $zdata;
  114. // "data descriptor" segment (optional but necessary if archive is not
  115. // served as file)
  116. $fr .= pack('V', $crc); // crc32
  117. $fr .= pack('V', $c_len); // compressed filesize
  118. $fr .= pack('V', $unc_len); // uncompressed filesize
  119. // add this entry to array
  120. $this -> datasec[] = $fr;
  121. // now add to central directory record
  122. $cdrec = "x50x4bx01x02";
  123. $cdrec .= "x00x00"; // version made by
  124. $cdrec .= "x14x00"; // version needed to extract
  125. $cdrec .= "x00x00"; // gen purpose bit flag
  126. $cdrec .= "x08x00"; // compression method
  127. $cdrec .= $hexdtime; // last mod time & date
  128. $cdrec .= pack('V', $crc); // crc32
  129. $cdrec .= pack('V', $c_len); // compressed filesize
  130. $cdrec .= pack('V', $unc_len); // uncompressed filesize
  131. $cdrec .= pack('v', strlen($name) ); // length of filename
  132. $cdrec .= pack('v', 0 ); // extra field length
  133. $cdrec .= pack('v', 0 ); // file comment length
  134. $cdrec .= pack('v', 0 ); // disk number start
  135. $cdrec .= pack('v', 0 ); // internal file attributes
  136. $cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set
  137. $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
  138. $this -> old_offset += strlen($fr);
  139. $cdrec .= $name;
  140. // optional extra field, file comment goes here
  141. // save to central directory
  142. $this -> ctrl_dir[] = $cdrec;
  143. } // end of the 'addFile()' method
  144. /**
  145. * Dumps out file
  146. *
  147. * @return string the zipped file
  148. *
  149. * @access public
  150. */
  151. function file()
  152. {
  153. $data = implode('', $this -> datasec);
  154. $ctrldir = implode('', $this -> ctrl_dir);
  155. return
  156. $data .
  157. $ctrldir .
  158. $this -> eof_ctrl_dir .
  159. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
  160. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
  161. pack('V', strlen($ctrldir)) . // size of central dir
  162. pack('V', strlen($data)) . // offset to start of central dir
  163. "x00x00"; // .zip file comment length
  164. }// end of the 'file()' method
  165. /**
  166. * A Wrapper of original addFile Function
  167. *
  168. * Created By Hasin Hayder at 29th Jan, 1:29 AM
  169. *
  170. * @param array An Array of files with relative/absolute path to be added in Zip File
  171. *
  172. * @access public
  173. */
  174. function addFiles($files /*Only Pass Array*/)
  175. {
  176. foreach($files as $file)
  177. {
  178. if (is_file($file)) //directory check
  179. {
  180. $data = implode("",file($file));
  181. $this->addFile($data,$file);
  182. }
  183. }
  184. }
  185. /**
  186. * A Wrapper of original file Function
  187. *
  188. * Created By Hasin Hayder at 29th Jan, 1:29 AM
  189. *
  190. * @param string Output file name
  191. *
  192. * @access public
  193. */
  194. function output($file)
  195. {
  196. $fp=fopen($file,"w");
  197. fwrite($fp,$this->file());
  198. fclose($fp);
  199. }
  200. } // end of the 'zipfile' class
复制代码

php, zip


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 does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment