search
HomeBackend DevelopmentPHP TutorialUnzip files using PHPZip

  1. #
  2. # PHPZip v1.2 by Sext (sext@neud.net) 2002-11-18
  3. # (Changed: 2003-03-01)
  4. #
  5. # Makes zip archive
  6. #
  7. # Based on "Zip file creation class", uses zLib
  8. #
  9. #
  10. class PHPZip
  11. {
  12. function Zip($dir, $zipfilename)
  13. {
  14. if (@function_exists('gzcompress'))
  15. {
  16. $curdir = getcwd();
  17. if (is_array($dir))
  18. {
  19. $filelist = $dir;
  20. }
  21. else
  22. {
  23. $filelist = $this -> GetFileList($dir);
  24. }
  25. if ((!empty($dir))&&(!is_array($dir))&&(file_exists($dir))) chdir($dir);
  26. else chdir($curdir);
  27. if (count($filelist)>0)
  28. {
  29. foreach($filelist as $filename)
  30. {
  31. if (is_file($filename))
  32. {
  33. $fd = fopen ($filename, "r");
  34. $content = fread ($fd, filesize ($filename));
  35. fclose ($fd);
  36. if (is_array($dir)) $filename = basename($filename);
  37. $this -> addFile($content, $filename);
  38. }
  39. }
  40. $out = $this -> file();
  41. chdir($curdir);
  42. $fp = fopen($zipfilename, "w");
  43. fwrite($fp, $out, strlen($out));
  44. fclose($fp);
  45. }
  46. return 1;
  47. }
  48. else return 0;
  49. }
  50. function GetFileList($dir)
  51. {
  52. if (file_exists($dir))
  53. {
  54. $args = func_get_args();
  55. $pref = $args[1];
  56. $dh = opendir($dir);
  57. while($files = readdir($dh))
  58. {
  59. if (($files!=".")&&($files!=".."))
  60. {
  61. if (is_dir($dir.$files))
  62. {
  63. $curdir = getcwd();
  64. chdir($dir.$files);
  65. $file = array_merge($file, $this -> GetFileList("", "$pref$files/"));
  66. chdir($curdir);
  67. }
  68. else $file[]=$pref.$files;
  69. }
  70. }
  71. closedir($dh);
  72. }
  73. return $file;
  74. }
  75. var $datasec = array();
  76. var $ctrl_dir = array();
  77. var $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
  78. var $old_offset = 0;
  79. /**
  80. * Converts an Unix timestamp to a four byte DOS date and time format (date
  81. * in high two bytes, time in low two bytes allowing magnitude comparison).
  82. *
  83. * @param integer the current Unix timestamp
  84. *
  85. * @return integer the current date in a four byte DOS format
  86. *
  87. * @access private
  88. */
  89. function unix2DosTime($unixtime = 0) {
  90. $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
  91. if ($timearray['year'] $timearray['year'] = 1980;
  92. $timearray['mon'] = 1;
  93. $timearray['mday'] = 1;
  94. $timearray['hours'] = 0;
  95. $timearray['minutes'] = 0;
  96. $timearray['seconds'] = 0;
  97. } // end if
  98. return (($timearray['year'] - 1980) ($timearray['hours'] > 1);
  99. }// end of the 'unix2DosTime()' method
  100. /**
  101. * Adds "file" to archive
  102. *
  103. * @param string file contents
  104. * @param string name of the file in the archive (may contains the path)
  105. * @param integer the current timestamp
  106. *
  107. * @access public
  108. */
  109. function addFile($data, $name, $time = 0)
  110. {
  111. $name = str_replace('', '/', $name);
  112. $dtime = dechex($this->unix2DosTime($time));
  113. $hexdtime = 'x' . $dtime[6] . $dtime[7]
  114. . 'x' . $dtime[4] . $dtime[5]
  115. . 'x' . $dtime[2] . $dtime[3]
  116. . 'x' . $dtime[0] . $dtime[1];
  117. eval('$hexdtime = "' . $hexdtime . '";');
  118. $fr = "x50x4bx03x04";
  119. $fr .= "x14x00"; // ver needed to extract
  120. $fr .= "x00x00"; // gen purpose bit flag
  121. $fr .= "x08x00"; // compression method
  122. $fr .= $hexdtime; // last mod time and date
  123. // "local file header" segment
  124. $unc_len = strlen($data);
  125. $crc = crc32($data);
  126. $zdata = gzcompress($data);
  127. $c_len = strlen($zdata);
  128. $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
  129. $fr .= pack('V', $crc); // crc32
  130. $fr .= pack('V', $c_len); // compressed filesize
  131. $fr .= pack('V', $unc_len); // uncompressed filesize
  132. $fr .= pack('v', strlen($name)); // length of filename
  133. $fr .= pack('v', 0); // extra field length
  134. $fr .= $name;
  135. // "file data" segment
  136. $fr .= $zdata;
  137. // "data descriptor" segment (optional but necessary if archive is not
  138. // served as file)
  139. $fr .= pack('V', $crc); // crc32
  140. $fr .= pack('V', $c_len); // compressed filesize
  141. $fr .= pack('V', $unc_len); // uncompressed filesize
  142. // add this entry to array
  143. $this -> datasec[] = $fr;
  144. $new_offset = strlen(implode('', $this->datasec));
  145. // now add to central directory record
  146. $cdrec = "x50x4bx01x02";
  147. $cdrec .= "x00x00"; // version made by
  148. $cdrec .= "x14x00"; // version needed to extract
  149. $cdrec .= "x00x00"; // gen purpose bit flag
  150. $cdrec .= "x08x00"; // compression method
  151. $cdrec .= $hexdtime; // last mod time & date
  152. $cdrec .= pack('V', $crc); // crc32
  153. $cdrec .= pack('V', $c_len); // compressed filesize
  154. $cdrec .= pack('V', $unc_len); // uncompressed filesize
  155. $cdrec .= pack('v', strlen($name) ); // length of filename
  156. $cdrec .= pack('v', 0 ); // extra field length
  157. $cdrec .= pack('v', 0 ); // file comment length
  158. $cdrec .= pack('v', 0 ); // disk number start
  159. $cdrec .= pack('v', 0 ); // internal file attributes
  160. $cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set
  161. $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
  162. $this -> old_offset = $new_offset;
  163. $cdrec .= $name;
  164. // optional extra field, file comment goes here
  165. // save to central directory
  166. $this -> ctrl_dir[] = $cdrec;
  167. } // end of the 'addFile()' method
  168. /**
  169. * Dumps out file
  170. *
  171. * @return string the zipped file
  172. *
  173. * @access public
  174. */
  175. function file()
  176. {
  177. $data = implode('', $this -> datasec);
  178. $ctrldir = implode('', $this -> ctrl_dir);
  179. return
  180. $data .
  181. $ctrldir .
  182. $this -> eof_ctrl_dir .
  183. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
  184. pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
  185. pack('V', strlen($ctrldir)) . // size of central dir
  186. pack('V', strlen($data)) . // offset to start of central dir
  187. "x00x00"; // .zip file comment length
  188. } // end of the 'file()' method
  189. }// end of the 'PHPZip' class
  190. ?>
  191. //Usage method
  192. $z = new PHPZip(); //Create a new zip class
  193. Method one:
  194. $z -> Zip("", "out1.zip"); //Add all files in the current directory and subdirectories
  195. Method 2:
  196. $files=array('1.txt','gb.txt');
  197. $files[]='5.txt';
  198. $z -> Zip($files, "out2.zip"); //Add file list
  199. Method 3:
  200. $z -> Zip("/ usr/local/sext/", "out3.zip"); //Add the specified directory
  201. ?>
Copy code

Unzip, PHPZip


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 modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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),

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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