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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools