PHP: Unzip the file into a zip and download it locally

Source: Internet
Author: User
Tags fread rewind save file unpack
This feature is not difficult to implement, first we have to find the path to this file. Then in the introduction of the third party class Phpzip this can be found on the Internet, I will post him out. A small partner in need can learn from it.

$name =  $_server[' document_root '). '/uploads/'. $folderName;               $this->tozip ($dir, "$name", 1, 1);
    The file is converted to the zip format    Function tozip ($Path, $ZipFile, $Typ = 1, $Todo = 1) {        //if (!is_writeable ($Path)) {Exit ("Folder not writable!");}        $Path = str_ireplace ("\", "/", ($Path));        IF (Is_null ($Path) or Empty ($Path) or! IsSet ($Path)) {            Return False;        }        IF (Is_null ($ZipFile) or Empty ($ZipFile) or! IsSet ($ZipFile)) {            Return False;        }         vendor ("Zip");//        echo $SERVER [' Document_root ']. " /zip.php ";        Include_once ($SERVER [' Document_root ']. " /zip.php "); Load the code base, note the path $zip = new \phpzip; IF (SubStr ($Path, 1, 1) = = "/") {$Path = SubStr ($Path, 0, StrLen ($Path)-1);} Ob_end_clean (); Switch ($TYP) {case "1": $zip->zipdir ($Path, $ZipFile, $Todo); break; Case "2": $zip->zipfile ($Path, $ZipFile, $Todo); break; } IF ($Todo = = 1) {die ();} Else {Return True;}}
Phpzip zip.php files are as follows:
 strpath);        Header (' Content-encoding:none ');        Header (' Content-type:application/zip '); Header (' content-disposition:attachment; Filename= '. Str_replace (". zip", "" ", BaseName ($zipfilename)).        Zip ');        Header (' Pragma:no-cache ');        Header (' expires:0 ');    Print ($out); }//Compressed after saving on the server, default in/@Upload Function SaveFile ($curdir, $zipfilename, $out) {$curdir =str_ireplace (basename ($curdi        R), "", $curdir);        ChDir ($curdir. $this->strpath);        $FP =fopen ($zipfilename, "WB");        Fwrite ($fp, $out, strlen ($out));    Fclose ($FP); }//function use: Compressed folder, recursive layer by//parameter detailed: $dir need to compress the directory, $zipfilename compressed file name and storage path, $Todo processing mode 1 provides download 2 save file in Server Function zipdir ($dir, $z        Ipfilename, $Todo) {IF (! @Function_exists (' gzcompress ')) {Return 0;}        @set_time_limit ("0");        $this->openfile ($dir, $zipfilename);        $out = $this-Filezip ();            Switch ($Todo) {case "1": $this-DownLoad (__file, $zipfilename, $out); break;       Case "2": SaveFile, $this (  FILE  , $zipfilename, $out);        break; }}//function: Compressed file, can be a single can also be an array of multiple//parameters in detail: $file need to compress the files (can be an array), $zipfilename the compressed file name and storage path, $Todo processing mode 1 provides download 2 save file in the server Func        tion ZipFile ($file, $zipfilename, $Todo) {IF (! @Function_exists (' gzcompress ')) {Return 0;} if (Is_array ($file)) {Foreach ($file as $filename) {IF (Is_file ($filename)) {$FD                    = fopen ($filename, "RB");                    $content = @fread ($FD, FileSize ($filename));                    Fclose ($FD);                    $filename = basename ($filename);                $this-AddFile ($content, $filename);                }}}else{IF (Is_file ($file)) {$fd = fopen ($file, "RB");                $content = @fread ($FD, FileSize ($file));                Fclose ($FD);                $file = basename ($file);            $this-AddFile ($content, $file);        }} $out = $this-Filezip (); Switch ($Todo) {       Case "1": DownLoad, $this ( FILE, $zipfilename, $out);        break; Case "2": SaveFile, $this (FILE, $zipfilename, $out);        break;        }}//Recursively get the file Function openFile ($path, $zipName) under the underlying folder {$temp _path= $path;        $temp _zip_path= $zipName;  if ($handle = @opendir ($path)) {while (False!== ($file =readdir ($handle))) {IF ($file! = '. ' and $file !='..') {IF (Ereg ('. ', $file. @basename ())) {$FD =fopen ($path. ')                        /'. $file, "R");                        $fileValue = @fread ($FD, 1024000);                        Fclose ($FD);                    $this-AddFile ($fileValue, '/'. $file); }else{$this->openfile ($path. ' /'. $file, $zipName. '                    /'. $file);        }}} $zipName = $temp _zip_path;        $path = $temp _path;        Closedir ($handle);        }} Function AddFile ($data, $name, $time =0) {$name =str_replace (' \ ', '/', $name); $name =str_replace ('./', ' ', 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";        $fr. = "\x00\x00";        $fr. = "\x08\x00";        $fr. = $hexdtime;        $unc _len=strlen ($data);        $CRC =crc32 ($data);        $zdata =gzcompress ($data);        $c _len=strlen ($zdata);        $zdata =substr (substr ($zdata, 0,strlen ($zdata)-4), 2);        $fr. =pack (' V ', $CRC);        $fr. =pack (' V ', $c _len);        $fr. =pack (' V ', $unc _len);        $fr. =pack (' V ', strlen ($name));        $fr. =pack (' V ', 0);        $fr. = $name;        $fr. = $zdata;        $fr. =pack (' V ', $CRC);        $fr. =pack (' V ', $c _len);        $fr. =pack (' V ', $unc _len);        $this-datasec[]= $fr;        $new _offset=strlen (Implode (", $this->datasec));        $cdrec = "\x50\x4b\x01\x02";        $cdrec. = "\x00\x00";        $cdrec. = "\x14\x00";        $cdrec. = "\x00\x00"; $cdrec. = "\x08\X00 ";        $cdrec. = $hexdtime;        $cdrec. =pack (' V ', $CRC);        $cdrec. =pack (' V ', $c _len);        $cdrec. =pack (' V ', $unc _len);        $cdrec. =pack (' V ', strlen ($name));        $cdrec. =pack (' V ', 0);        $cdrec. =pack (' V ', 0);        $cdrec. =pack (' V ', 0);        $cdrec. =pack (' V ', 0);        $cdrec. =pack (' V ', 32);        $cdrec. =pack (' V ', $this-old_offset);        $this, old_offset= $new _offset;        $cdrec. = $name;    $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)).        Pack (' V ', sizeof ($this-Ctrl_dir)).        Pack (' V ', strlen ($ctrldir)). Pack (' V ', strlen ($data)). "    \x00\x00 ";        } 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; } Return (($timearray [' Year ']-1980) << 25) | ($timearray [' mon '] << 21) | ($timearray [' Mday '] << 16) | ($timearray [' hours '] << 11) | ($timearray [' minutes '] << 5) |    ($timearray [' seconds '] >> 1);         }/Extract part of the purpose: Extract the file parameters: $zn The zip file and path to extract, $to the extracted destination/Function unzip_file ($ZN, $to, $index = Array (-1)) {        $ok = 0;        $zip = @fopen ($ZN, ' RB ');        IF (! $zip) {Return (-1);}        $cdir = Readcentraldir ($zip, $ZN), $this        $pos _entry = $cdir [' offset '];        IF (!is_array ($index)) {$index = array ($index); } for ($i = 0; $index [$i]; $i + +) {IF (Intval ($index [$i])! = $index [$i] | | $index [$i] > $cdir [' Entries ']) {        Return (-1);}     } for ($i =0; $i < $cdir [' entries ']; $i + +) {       @fseek ($zip, $pos _entry);            $header = $this-Readcentralfileheaders ($zip);            $header [' index '] = $i;            $pos _entry = Ftell ($zip);            @rewind ($zip);            Fseek ($zip, $header [' offset ']); IF (In_array ("1", $index) | | In_array ($i, $index)) {$stat [$header [' filename ']] = $this, Extractfile ($header, $to, $        Zip);}        } fclose ($zip);    Return $stat;        }//Get the file information inside the compressed package Function get_list ($zip _name) {$zip = @fopen ($zip _name, ' RB ');        IF (! $zip) {Return (0);}        $centd = Readcentraldir $this, $zip, $zip _name);        @rewind ($zip);        @fseek ($zip, $centd [' offset ']);            for ($i =0; $i < $centd [' entries ']; $i + +) {$header = $this, readcentralfileheaders ($zip);            $header [' index '] = $i;            $info [' filename '] = $header [' filename '];            $info [' stored_filename '] = $header [' Stored_filename '];            $info [' size '] = $header [' Size ']; $info [' CompresSed_size '] = $header [' compressed_size '];            $info [' CRC '] = Strtoupper (Dechex ($header [' CRC ']);            $info [' mtime '] = $header [' Mtime '];            $info [' comment '] = $header [' comment '];            $info [' folder '] = ($header [' external '] = = 0x41ff0010 | | $header [' external '] = = 16)? 1:0;            $info [' index '] = $header [' index '];            $info [' status '] = $header [' status '];            $ret [] = $info;        Unset ($header);    } Return $ret;        } Function Readfileheader ($zip) {$binary _data = fread ($zip, 30); $data = Unpack (' vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/vcrc/vcompressed_size/vsize/vfilename_len/        Vextra_len ', $binary _data);        $header [' filename '] = fread ($zip, $data [' Filename_len ']); IF ($data [' Extra_len ']! = 0) {$header [' extra '] = Fread ($zip, $data [' Extra_len ']);}        else{$header [' extra '] = ';}        $header [' compression '] = $data [' compression '];        $header [' size '] = $data [' Size ']; $header [' compressed_sIze '] = $data [' compressed_size '];        $header [' CRC '] = $data [' CRC '];        $header [' flag '] = $data [' flag '];        $header [' mdate '] = $data [' mdate '];        $header [' mtime '] = $data [' Mtime '];            IF ($header [' mdate '] && $header [' mtime ']) {$hour = ($header [' Mtime ']&0xf800) >> 11;            $minute = ($header [' Mtime ']&0x07e0) >> 5;            $seconde = ($header [' Mtime ']&0x001f) 2;            $year = (($header [' mdate ']&0xfe00) >> 9) + 1980;            $month = ($header [' mdate ']&0x01e0) >> 5;            $day = $header [' Mdate ']&0x001f;        $header [' mtime '] = Mktime ($hour, $minute, $seconde, $month, $day, $year);        }else{$header [' mtime '] = time ();        } $header [' stored_filename '] = $header [' filename '];        $header [' status '] = "OK";    Return $header;        } Function readcentralfileheaders ($zip) {$binary _data = fread ($zip, 46); $header = Unpack (' Vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/vcrc/vcompressed_size/vsize/vfilename_len/vextra_len/        Vcomment_len/vdisk/vinternal/vexternal/voffset ', $binary _data);        IF ($header [' Filename_len ']! = 0) $header [' filename '] = fread ($zip, $header [' Filename_len ']);        Else $header [' filename '] = ';        IF ($header [' Extra_len ']! = 0) $header [' extra '] = Fread ($zip, $header [' Extra_len ']);        Else $header [' extra '] = ';        IF ($header [' Comment_len ']! = 0) $header [' comment '] = fread ($zip, $header [' Comment_len ']);        Else $header [' comment '] = ';            IF ($header [' mdate '] && $header [' mtime ']) {$hour = ($header [' mtime '] &0xf800) >> 11;            $minute = ($header [' mtime '] &0x07e0) >> 5;            $seconde = ($header [' mtime '] &0x001f) 2;            $year = (($header [' mdate '] &0xfe00) >> 9) + 1980;            $month = ($header [' mdate '] &0x01e0) >> 5; $day = $header[' Mdate ' &0x001F;        $header [' mtime '] = Mktime ($hour, $minute, $seconde, $month, $day, $year);        }else{$header [' mtime '] = time ();        } $header [' stored_filename '] = $header [' filename '];        $header [' status '] = ' OK ';        IF (substr ($header [' filename '],-1) = = '/') $header [' external '] = 0x41ff0010;    Return $header;        } Function Readcentraldir ($zip, $zip _name) {$size = FileSize ($zip _name); IF ($size < 277) {$maximum _size = $size;}        else{$maximum _size = 277;}        @fseek ($zip, $size-$maximum _size);        $pos = Ftell ($zip);        $bytes = 0x00000000;            while ($pos < $size) {$byte = @fread ($zip, 1); $bytes = ($bytes << 8) |            Ord ($byte);                IF ($bytes = = 0x504b0506) {$pos + +;            Break        } $pos + +;    } $data = Unpack (' Vdisk/vdisk_start/vdisk_entries/ventries/vsize/voffset/vcomment_size ', Fread ($zip, 18));    IF ($data [' comment_size ']! = 0) {$centd [' comment '] = fread ($zip, $data [' comment_size ']);}        else{$centd [' comment '] = ';}        $centd [' entries '] = $data [' Entries '];        $centd [' disk_entries '] = $data [' disk_entries '];        $centd [' offset '] = $data [' offset '];        $centd [' disk_start '] = $data [' Disk_start '];        $centd [' size '] = $data [' Size '];        $CENTD [' disk '] = $data [' Disk '];    Return $centd;        } Function Extractfile ($header, $to, $zip) {$header = $this, Readfileheader ($zip);        IF (substr ($to,-1)! = "/") $to. = "/";        IF (! @is_dir ($to)) @mkdir ($to, 0777);        $pth = Explode ("/", DirName ($header [' filename ']);            for ($i = 0;isset ($pth [$i]), $i + +) {IF (! $pth [$i]) continue; $pthss. = $pth [$i].            "/";        IF (!is_dir ($to. $pthss)) @mkdir ($to. $PTHSS, 0777); } IF (! ( $header [' external '] = = 0x41ff0010) &&! ($header [' external '] = = 16)) {IF ($header [' compression '] = = 0) {$fp = @fopen ($to. $header [' filename '], ' WB ');                IF (! $fp) Return (-1);                $size = $header [' compressed_size '];                    while ($size! = 0) {$read _size = ($size < 2048? $size: 2048);                    $buffer = Fread ($zip, $read _size);                    $binary _data = Pack (' a '. $read _size, $buffer);                    @fwrite ($fp, $binary _data, $read _size);                $size-= $read _size;                } fclose ($FP);            Touch ($to. $header [' filename '], $header [' mtime ']; }else{$fp = @fopen ($to. $header [' filename '].                '. Gz ', ' WB ');                IF (! $fp) Return (-1); $binary _data = Pack (' va1a1va1a1 ', 0x8b1f, Chr ($header [' compression ']), Chr (0x00), Time (), Chr (0x00), Ch                R (3));                Fwrite ($fp, $binary _data, 10);                $size = $header [' compressed_size ']; while ($size! = 0) {$read _size = ($siZe < 1024?                    $size: 1024);                    $buffer = Fread ($zip, $read _size);                    $binary _data = Pack (' a '. $read _size, $buffer);                    @fwrite ($fp, $binary _data, $read _size);                $size-= $read _size;                } $binary _data = Pack (' VV ', $header [' CRC '], $header [' size '];                Fwrite ($fp, $binary _data, 8);                Fclose ($FP); $GZP = @gzopen ($to. $header [' filename '].                '. Gz ', ' RB ') or die ("Cette archive est compress casual");                IF (! $gzp) Return (-2);                $fp = @fopen ($to. $header [' filename '], ' WB ');                IF (! $fp) Return (-1);                $size = $header [' Size '];                    while ($size! = 0) {$read _size = ($size < 2048? $size: 2048);                    $buffer = Gzread ($gzp, $read _size);                    $binary _data = Pack (' a '. $read _size, $buffer);                    @fwrite ($fp, $binary _data, $read _size);$size-= $read _size;                } fclose ($FP);                Gzclose ($GZP);                Touch ($to. $header [' filename '], $header [' mtime ']; @unlink ($to. $header [' filename '].            '. Gz ');    }} Return true; }}
  • 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.