The PHP implementation compresses multiple files into a zip format and downloads them to a local

Source: Internet
Author: User
Tags bit set crc32 time and date ziparchive
This article mainly introduces the implementation of PHP to compress multiple files into a zip format and download to the local method, involving PHP for file and directory read and write, judge and zip compression related operation skills, the need for friends can refer to the next

The example in this article describes how PHP is implemented to compress multiple files into a zip format and download them locally. Share to everyone for your reference, as follows:

Nonsense not much to say directly on the code

It is important to note that the directory exists and that there is permission to create $zipname = ' path/test.zip '//This is an array of file addresses to package $files = Array ("Mypath/test1.txt", "mypath/ Test2.pdf "), $zip = new Ziparchive (), $res = $zip->open ($zipname, Ziparchive::create), if ($res = = = TRUE) {foreach ($file S as $file) {//here directly with the name of the original file package, you can also directly name, you need to note that if the file name will cause the following file overwrite the previous file, it is recommended to rename  $new _filename = substr ($file, Strrpos ($file, '/') + 1);  $zip->addfile ($file, $new _filename); }}//close File $zip->close ();

Here is the download zip file header ("Content-type:application/zip"); Header ("Content-transfer-encoding:binary"); Header (" Content-length: ". FileSize ($zipname)); header ("Content-disposition:attachment; Filename=\ "". BaseName ($zipname). "\" "); ReadFile ($zipname); exit;

attached: here to provide you with a zip compression class:

<?php# # Phpzip v1.2 by Sext (sext@neud.net) 2002-11-18# (changed:2003-03-01) # # makes zip archive## Based on "Zip F    Ile Creation Class ", uses zlib# #class phpzip{function Zip ($dir, $zipfilename) {if (@function_exists (' gzcompress '))      {$curdir = GETCWD ();      if (Is_array ($dir)) {$filelist = $dir;      } else {$filelist = $this-Getfilelist ($dir);      } if ((!empty ($dir)) && (!is_array ($dir)) && (File_exists ($dir))) chdir ($dir);      else ChDir ($curdir);          if (count ($filelist) >0) {foreach ($filelist as $filename) {if (Is_file ($filename))            {$fd = fopen ($filename, "R");            $content = Fread ($FD, FileSize ($filename));            Fclose ($FD);            if (Is_array ($dir)) $filename = basename ($filename);          $this-AddFile ($content, $filename);        }} $out = $this file ();        ChDir ($curdir); $fp = fOpen ($zipfilename, "w");        Fwrite ($fp, $out, strlen ($out));      Fclose ($FP);    } return 1;  } else return 0;      } function Getfilelist ($dir) {if (file_exists ($dir)) {$args = Func_get_args ();      $pref = $args [1];      $DH = Opendir ($dir); while ($files = Readdir ($DH)) {if ($files! = ".")         && ($files! = "..."))            {if (Is_dir ($dir. $files)) {$curdir = GETCWD ();            ChDir ($dir. $files);            $file = Array_merge ($file, $this, Getfilelist ("", "$pref $files/"));          ChDir ($curdir);        The Else $file []= $pref. $files;    }} closedir ($DH);  } return $file;  } var $datasec = array ();  var $ctrl _dir = Array ();  var $eof _ctrl_dir = "x50x4bx05x06x00x00x00x00";  var $old _offset = 0; /** * Converts an Unix timestamp-a four byte-DOS date and time format (date * in high-bytes, time in.   TES allowing magnitude comparison). * * @paRam integer the current Unix timestamp * * @return An integer, the current date, a four byte DOS format * * @access    Private */function unix2dostime ($unixtime = 0) {$timearray = ($unixtime = = 0)? getdate (): getdate ($unixtime);      if ($timearray [' Year '] < 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); }//End of the ' unix2dostime () ' Method/** * Adds "file" to archive * * @param string file contents * @param St Ring name of the file in the archive (may contains the path) * @param an integer the current timestamp * * @access Pub LIC */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 = "x50x4bx03x04";      $fr. = "x14x00";      Ver needed to extract $fr. = "x00x00";      Gen purpose bit flag $fr. = "x08x00";       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 = "x50x4bx01x02";        $cdrec. = "x00x00";        Version made by $cdrec. = "x14x00";        Version needed to extract $cdrec. = "x00x00";        Gen purpose bit flag $cdrec. = "x08x00";         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;   }//End of the ' AddFile () ' method/** * Dumps out file * * @return String The zipped file * * @access public    */function file () {$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 "x00x00"; . zip file Comment Length}//End of the ' file () ' method}//End of the ' Phpzip ' class?>

Usage:

$zipfiles =array ("/root/pooy/test1.txt", "/root/pooy/test2.txt"), $z = new Phpzip ();//$randomstr = random (8); $zipfile = TEMP. " /photocome_ ". $groupid.". Zip "; $z->zip ($zipfiles, $zipfile);

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.