How to use PHP to generate zip compressed files with detailed code

Source: Internet
Author: User
Tags bit set crc32 create zip time and date
The code is as follows:

Require_once "./include/zip.php"; $zip = new Phpzip ();   $zip-Createzip ("folder directory address to compress", "compressed file name. zip");  Generate only non-automatic downloads $zip-downloadzip ("folder directory address to compress", "compressed file name. zip"); Automatic download

Example: You can refer to the following pseudo-code to see a specific usage scenario:

The code is as follows:

Require_once "./include/zip.php"; if (! $download) {exit ();} set_time_limit (60); $tmpManager = new Tmpmanager (); Suppose we have a class to do the following $tempfolder = Array (); $tempfile = Array (); Let's say we download the selected folder or file by selecting the checkbox on the page, and package for ($i = 0; $i < $checkboxnum; $i + +) {$value = ${"select". $i}; if ($value! = ' ') {$this _type = substr ($value, 0, 1), $this _id = substr ($value, 1);//separate folder and file processing if ($this _type = = ' d ') {$tempfolde r[] = $this _id; } elseif ($this _type = = ' F ') {$tempfile [] = $this _id;}} } @mkdir ($tempdir); $curtempdir = "$tempdir/". $userid; Different users operate under different temporary folders if (file_exists ($curtempdir)) {$tmpManager->deletedir ($curtempdir);//delete old folder} if (sizeof ($ TempFolder) > 0 | | sizeof ($tempfile) > 0) {mkdir ($curtempdir, 0777);//If you have a file folder to package, re-create the folder} if (sizeof ($tempfile) > 0) {$tmpManage R->copyfile ($tempfile, $curtempdir); Copy the file you want to download to the folder you created} if (sizeof ($tempfolder) > 0) {$tmpManager->copyfolder ($tempfolder, $curtempdir); Copy the folder you want to download to the folder you created} $zip = new Phpzip(); $zip-Downloadzip ($curtempdir, "File_". Date (' Ymd '). ". Zip "); Package and download

zip.php

The code is as follows:

<?php/* File name:/include/zip.php author:horace 2009/04/15 */class phpzip{var $dirInfo = Array ("0", "0"), var $roo Tdir = "; var $datasec = array (); var $ctrl _dir = Array (); var $eof _ctrl_dir = "/x50/x4b/x05/x06/x00/x00/x00/x00"; var $old _offset = 0; function Downloadzip () {createzip ($dir, $zipfilename, True),} function Createzip ($dir, $zipfilename, $autoDownload = FAL  SE) {if (@function_exists (' gzcompress ')) {@set_time_limit ("0"), if (Is_array ($dir)) {$fd = fopen ($dir, "R"); $fileValue = Fread ($FD, FileSize ($filename)); Fclose ($FD); if (Is_array ($dir)) $filename = basename ($dir); $this-AddFile ($fileValue, "$filename"); }else{$this->dirtree ($dir, $dir);} $zipfilenametemp = time (). $zipfilename; $out = $this-Filezip (); $fp = fopen ($zipfilenametemp, "w"); Fwrite ($fp, $out, strlen ($out)); Fclose ($FP); $filesize = FileSize ($zipfilenametemp); if ($filesize < 104857600) {if ($autoDownload) {header ("Content-type:application/octet-stream"); Header (" Content-disposItion:attachment; Filename= ". $zipfilename); } Echo $this-Filezip (); }else{echo "Create Zip error!";} unlink ($zipfilenametemp); }}//get dir tree. function DirTree ($directory, $rootDir) {Global $_server, $dirInfo, $rootDir; $fileDir = $rootDir; $myDir =dir ($directory) ; while ($file = $myDir->read ()) {if (Is_dir ("$directory/$file") and $file! = "." and $file! = "...") {$dirInfo [0]++; $rootDir = "$fileDir $file/"; $this, AddFile ("," $rootDir "),//go on n ' s folders $this->dirtree (" $ directory/$file ", $rootDir); }else{if ($file! = "." and $file! = "...") {$dirInfo [1]++;//$fd = fopen ("$directory/$file", "R"), $fileValue = file_get_contents ("$directory/$file");//fclose ($ FD); $this-AddFile ($fileValue, "$fileDir $file"); }}} $myDir->close (); } function unix2dostime ($unixtime = 0) {$timearray = ($unixtime = = 0)? getdate (): getdate ($unixtime); if ($timearray [' Y Ear '] < 1980) {$timearray [' year '] = 1980; $timearray [' mon '] = 1; $timearray [' mday '] = 1; $timearray [' hours '] = 0; $timearray[' minutes '] = 0; $timearray [' seconds '] = 0; }//End If return (($timearray [' Year ']-1980) << 25) | ($timearray [' mon '] << 21) | ($timearray [' Mday '] << 16) | ($timearray [' hours '] << 11) | ($timearray [' minutes '] << 5) | ($timearray [' seconds '] >> 1); } function AddFile ($data, $name, $time = 0) {$name = Str_replace ('//', '/', $name); $dtime = Dechex ($this->unix2dostime ($time)); $hexdtime = '/x '. $dtime [6]. $dtime [7]. '/x '. $dtime [4]. $dtime [5]. '/x '. $dtime [2]. $dtime [3]. '/x '. $dtime [0]. $dtime [1]; Eval (' $hexdtime = '. $hexdtime. '";'); $FR = "/x50/x4b/x03/x04"; $fr. = "/x14/x00"; Ver needed to extract $fr. = "/x00/x00"; Gen purpose bit flag $fr. = "/x08/x00"; Compression method $fr. = $hexdtime; Last mod time and date//"Local file Header" segment $unc _len = strlen ($data); $CRC = CRC32 ($data); $zdata = gzcompress ($data); $c _len = strlen ($zdata); $zdata = substr (substr ($zdata, 0, strlen ($zdata)-4), 2); Fix CRC BUG $fr. = Pack (' V ', $CRC); CRC32 $fr. = Pack (' V ', $c _len); Compressed filesize $fr. = Pack (' V ', $unc _len); Uncompressed filesize $fr. = Pack (' V ', strlen ($name)); Length of filename $fr. = Pack (' V ', 0); Extra field length $fr. = $name; "File Data" segment $fr. = $zdata; "Data Descriptor" segment (optional but necessary if archive are not//served as file) $fr. = Pack (' V ', $CRC); CRC32 $fr. = Pack (' V ', $c _len); Compressed filesize $fr. = Pack (' V ', $unc _len); Uncompressed FileSize//Add this entry to array $this-datasec[] = $FR; $new _offset = strlen (Implode (", $this->datasec)); Now the add to central directory record $cdrec = "/x50/x4b/x01/x02"; $cdrec. = "/x00/x00"; Version made by $cdrec. = "/x14/x00"; Version needed to extract $cdrec. = "/x00/x00"; Gen purpose bit flag $cdrec. = "/x08/x00"; Compression method $cdrec. = $hexdtime; Last mod time & date $cdrec. = Pack (' V ', $CRC); CRC32 $cdrec. = Pack (' V ', $c _len); Compressed FileSize $cdrec. = Pack (' V ', $unc _len); Uncompressed filesize $cdrec. = Pack (' V ', strlen ($name)); Length of filename $cdrec. = Pack (' V ', 0); Extra field length $cdrec. = Pack (' V ', 0); File comment length $cdrec. = Pack (' V ', 0); Disk number start $cdrec. = Pack (' V ', 0); Internal file attributes $cdrec. = Pack (' V ', 32); External file attributes-' archive ' bit set $cdrec. = Pack (' V ', $this-old_offset); Relative offset of the local header $this-old_offset = $new _offset; $cdrec. = $name; Optional extra field, file comment goes here//save to Central directory $this, ctrl_dir[] = $cdrec;  } function Filezip () {$data = Implode (", $this-datasec); $ctrldir = Implode (", $this-Ctrl_dir); return $data . $ctrldir. Eof_ctrl_dir, $this. Pack (' V ', sizeof ($this-Ctrl_dir)). Total # of Entries "on this disk" pack (' V ', sizeof ($this-Ctrl_dir)). Total # of Entries Overall pack (' V ', strlen ($ctrldir)). Size of CentraL dir Pack (' V ', strlen ($data)). Offset to start of the central dir "/x00/x00"; . zip file comment length}}?>

Related articles:

Generate Zip Compressed files from PHP, support file and archive path lookup

PHP implementation of online decompression zip archive

Simple PHP method for creating Zip compressed files

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.