首页 > 编程语言 >PHP实现将多个文件压缩成zip格式并下载到本地

PHP实现将多个文件压缩成zip格式并下载到本地

时间:2023-03-04 10:35:49浏览次数:47  
标签:fr zip cdrec 压缩成 file PHP dir pack

 1 //这里需要注意该目录是否存在,并且有创建的权限
 2 $zipname = 'path/test.zip'
 3 //这是要打包的文件地址数组
 4 $files = array("mypath/test1.txt","mypath/test2.pdf");
 5 $zip = new ZipArchive();
 6 $res = $zip->open($zipname, ZipArchive::CREATE);
 7 if ($res === TRUE) {
 8  foreach ($files as $file) {
 9  //这里直接用原文件的名字进行打包,也可以直接命名,需要注意如果文件名字一样会导致后面文件覆盖前面的文件,所以建议重新命名
10   $new_filename = substr($file, strrpos($file, '/') + 1);
11   $zip->addFile($file, $new_filename);
12  }
13 }
14 //关闭文件
15 $zip->close();
16 //这里是下载zip文件
17 header("Content-Type: application/zip");
18 header("Content-Transfer-Encoding: Binary");
19 header("Content-Length: " . filesize($zipname));
20 header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\"");
21 readfile($zipname);
22 exit;

 

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

 

标签:fr,zip,cdrec,压缩成,file,PHP,dir,pack
From: https://www.cnblogs.com/gwhm/p/17177749.html

相关文章

  • centos7.9编译安装libzip-1.9.2 和 cmake 3.23.0
    centos7.9编译安装libzip-1.9.2在编译安装php时系统会报configure:error:Packagerequirements(libzip>=0.11libzip!=1.3.1libzip!=…这是因为libzip版本过......
  • Laravel运行项目提示/composer/autoload_real.php问题
    1.确保已安装Composer。如果没有请安装.安装步骤参考:http://www.360doc.com/content/22/0919/15/65839921_1048527526.shtml2.进入Laraver项目的根目录,通过命令窗口执行......
  • Linux运用一些常用命令,优秀的PHPer都需掌握
    作为一名优秀的phper,Linux是必备的一项技能,工作3-5年的基本能明白我讲的道理!今天搜集整理了一些Linux服务器运维常用命令,希望对大家有帮助:1.删除0字节文件 find -type......
  • zip文件结构
    转starshine博客压缩源文件数据区:504B0304:这是头文件标记(0x04034b50)1400:解压文件所需pkware版本0000:全局方式位标记(有无加密)0800:压缩方式5A7E:最后修改文件......
  • PHP8安装(centos7环境)
    一、事先安装的模块yuminstall-ybzip2-devellibcurl-devellibxml2-develsqlite-develonigurumaoniguruma-devellibxml2libxml2-develbzip2bzip2-devellibcurl......
  • PHP 常见字符串函数
    1、字符串格式化1、trim():删除字符串两端的空格或其他预定义字符2、rtrim():删除字符串右边的空格或其他预定义字符3、ltrim():删除字符串左边的空格或其他预定义......
  • php之Opcache深入理解
    PHP项目中,尤其是在高并发大流量的场景中,如何提升PHP的响应时间,是一项十分重要的工作。而Opcache又是优化PHP性能不可缺失的组件,尤其是应用了PHP框架的项目中,作用更是明显。......
  • PHP介绍和基础知识
    PHP(外文名:PHP:HypertextPreprocessor,中文名:“超文本预处理器”)是一种通用开源的、简单的,面向对象的,解释型的,健壮的,安全的,性能非常之高的,独立于架构的,可移植的,动态的脚......
  • PHP写UltraEdit插件脚本实现方法
    UltraEdit可以扩展许多函数来减少我们编写的体力劳动,这个功能的调用是比较实用的,下面是给大家带来的PHP写UltraEdit插件脚本实现方法,一起进入下文了解一下吧!需求:1svn上的......
  • linux php8.x 编译安装
    安装各种依赖yum-yinstallwgetvimpcrepcre-developensslopenssl-devellibicu-develgccgcc-c++autoconflibjpeglibjpeg-devellibpnglibpng-develfreetype......