1 <?php 2 /** 3 * 關於文件壓縮和下載的類 4 * @author tycell 5 * @version 1.0 6 */ 7 class zip_down{ 8 9 protected $file_path; 10 /** 11 * 構造函數 12 * @param [string] $path [傳入文件目錄] 13 */ 14 public function __construct($path){ 15 $this->file_path=$path; //要打包的根目錄 16 } 17 /** 18 * 入口調用函數 19 * @return [type] [以二進制流的形式返回給瀏覽器下載到本地] 20 */ 21 public function index(){ 22 $zip=new ZipArchive(); 23 $end_dir=$this->file_path.date('Ymd',time()).'.zip';//定義打包后的包名 24 $dir=$this->file_path; 25 if(!is_dir($dir)){ 26 mkdir($dir); 27 } 28 if($zip->open($end_dir, ZipArchive::OVERWRITE) === TRUE){ ///ZipArchive::OVERWRITE 如果文件存在則覆蓋 29 $this->addFileToZip($dir, $zip); //調用方法,對要打包的根目錄進行操作,並將ZipArchive的對象傳遞給方法 30 $zip->close(); 31 } 32 if(!file_exists($end_dir)){ 33 exit("無法找到文件"); 34 } 35 header("Cache-Control: public"); 36 header("Content-Description: File Transfer"); 37 header("Content-Type: application/zip"); //zip格式的 38 header('Content-disposition: attachment; filename='.basename($end_dir)); //文件名 39 header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進制文件 40 header('Content-Length:'.filesize($end_dir)); //告訴瀏覽器,文件大小 41 @readfile($end_dir); 42 $this->delDirAndFile($dir,true);//刪除目錄和文件 43 unlink($end_dir);////刪除壓縮包 44 } 45 /** 46 * 文件壓縮函數 需要開啟php zip擴展 47 * @param [string] $path [路徑] 48 * @param [object] $zip [擴展ZipArchive類對象] 49 */ 50 protected function addFileToZip($path, $zip){ 51 $handler = opendir($path); 52 while (($filename=readdir($handler)) !== false) { 53 if ($filename!= "." && $filename!=".."){ 54 if(!is_dir($filename)){ 55 $zip->addFile($path."/".$filename,$filename); //第二個參數避免將目錄打包,可以不加 56 } 59 } 60 } 61 @closedir($path); 62 } 63 /** 64 * 刪除文件函數 65 * @param [string] $dir [文件目錄] 66 * @param boolean $delDir [是否刪除目錄] 67 * @return [type] [description] 68 */ 69 protected function delDirAndFile($path,$delDir=true){ 70 $handle=opendir($path); 71 if($handle){ 72 while(false!==($item = readdir($handle))){ 73 if($item!="."&&$item!=".."){ 74 if(is_dir($path.'/'.$item)){ 75 $this->delDirAndFile($path.'/'.$item, $delDir); 76 }else{ 77 unlink($path.'/'.$item); 78 } 79 } 80 } 81 @closedir($handle); 82 if($delDir){return rmdir($path);} 83 }else{ 84 if(file_exists($path)){ 85 return unlink($path); 86 }else{ 87 return FALSE; 88 } 89 } 90 } 91 92 }
