標籤:func overwrite amp sts family logs pen log protected
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($path."/".$filename)){55 $this->addFileToZip($path."/".$filename,$zip);56 } else {57 $zip->addFile($path."/".$filename);58 } 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 }
PHP擴充類ZipArchive實現壓縮Zip檔案和檔案打包下載