yllplay 发表于 2017-12-30 21:55:35

PHP扩展类ZipArchive实现压缩Zip文件和文件打包下载

<?php  

/**  

* 关于文件压缩和下载的类  

* @authortycell  

* @version 1.0  

*/
  
>  

  
   protected $file_path;
  
   /**
  
      * 构造函数
  
      * @param $path [传入文件目录]
  
      */
  
   public function __construct($path){
  
         $this->file_path=$path; //要打包的根目录
  
   }
  
   /**
  
      * 入口调用函数
  
      * @return [以二进制流的形式返回给浏览器下载到本地]
  
      */
  
   public function index(){
  
         $zip=new ZipArchive();
  
         $end_dir=$this->file_path.('Ymd',()).'.zip';//定义打包后的包名
  
         $dir=$this->file_path;
  
         if(!($dir)){
  
             ($dir);
  
         }
  
         if($zip->open($end_dir, ZipArchive::OVERWRITE) === TRUE){ ///ZipArchive::OVERWRITE 如果文件存在则覆盖
  
             $this->addFileToZip($dir, $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
  
             $zip->close();
  
         }
  
         if(!($end_dir)){
  
             exit("无法找到文件");
  
         }
  
         ("Cache-Control: public");
  
         ("Content-Description: File Transfer");
  
         ("Content-Type: application/zip"); //zip格式的
  
         ('Content-disposition: attachment; filename='.($end_dir)); //文件名
  
         ("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
  
         ('Content-Length:'.($end_dir)); //告诉浏览器,文件大小
  
         @($end_dir);
  
         $this->delDirAndFile($dir,true);//删除目录和文件
  
         ($end_dir);////删除压缩包
  
   }
  
   /**
  
      * 文件压缩函数 需要开启php zip扩展
  
      * @param $path [路径]
  
      * @param $zip[扩展ZipArchive类对象]
  
      */
  
   protected function addFileToZip($path, $zip){
  
         $handler = ($path);
  
         while (($filename=($handler)) !== false) {
  
             if ($filename!= "." && $filename!=".."){
  
                if(($path."/".$filename)){
  
                     $this->addFileToZip($path."/".$filename,$zip);
  
               } else {
  
                     $zip->addFile($path."/".$filename);
  
               }
  
             }
  
         }
  
         @($path);
  
   }
  
   /**
  
      * 删除文件函数
  
      * @param$dir    [文件目录]
  
      * @paramboolean $delDir [是否删除目录]
  
      * @return          
  
      */
  
   protected function delDirAndFile($path,$delDir=true){
  
         $handle=($path);
  
         if($handle){
  
             while(false!==($item = ($handle))){
  
               if($item!="."&&$item!=".."){
  
                     if(($path.'/'.$item)){
  
                         $this->delDirAndFile($path.'/'.$item, $delDir);
  
                     }else{
  
                         ($path.'/'.$item);
  
                     }
  
               }
  
             }
  
             @($handle);
  
             if($delDir){return ($path);}
  
         }else{
  
             if(($path)){
  
               return ($path);
  
             }else{
  
               return FALSE;
  
             }
  
         }
  
   }
  

  
}
页: [1]
查看完整版本: PHP扩展类ZipArchive实现压缩Zip文件和文件打包下载