search
HomeBackend DevelopmentPHP TutorialPHP packages a set of files into a zip package.

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


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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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