php
2/** 3 * 关于文件压缩和下载的类 4 * @author tycell 5 * @version 1.0 6*/ 7class zip_down{ 8 9protected$file_path; 10/** 11 * 构造函数 12 * @param [string] $path [传入文件目录] 13*/14publicfunction__construct(
$path){ 15$this->file_path=
$path;
//要打包的根目录16 } 17/** 18 * 入口调用函数 19 * @return [type] [以二进制流的形式返回给浏览器下载到本地] 20*/21publicfunction index(){ 22$zip=
new ZipArchive(); 23$end_dir=
$this->file_path.
date(‘Ymd‘,
time()).‘.zip‘;
//定义打包后的包名24$dir=
$this->
file_path; 25if(!
is_dir(
$dir)){ 26mkdir(
$dir); 27 } 28if(
$zip->open(
$end_dir, ZipArchive::OVERWRITE) ===
TRUE){
///ZipArchive::OVERWRITE 如果文件存在则覆盖29$this->addFileToZip(
$dir,
$zip);
//调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法30$zip->
close(); 31 } 32if(!
file_exists(
$end_dir)){ 33exit("无法找到文件"
); 34 } 35header("Cache-Control: public"
); 36header("Content-Description: File Transfer"
); 37header("Content-Type: application/zip");
//zip格式的 38header(‘Content-disposition: attachment; filename=‘.
basename(
$end_dir));
//文件名 39header("Content-Transfer-Encoding: binary");
//告诉浏览器,这是二进制文件 40header(‘Content-Length:‘.
filesize(
$end_dir));
//告诉浏览器,文件大小 41@
readfile(
$end_dir); 42$this->delDirAndFile(
$dir,
true);
//删除目录和文件43unlink(
$end_dir);
////删除压缩包44 } 45/** 46 * 文件压缩函数 需要开启php zip扩展 47 * @param [string] $path [路径] 48 * @param [object] $zip [扩展ZipArchive类对象] 49*/50protectedfunctionaddFileToZip(
$path,
$zip){ 51$handler=
opendir(
$path); 52while((
$filename=
readdir(
$handler)) !==
false) { 53if(
$filename!= "." &&
$filename!=".."
){ 54if(
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*/69protectedfunctiondelDirAndFile(
$path,
$delDir=
true){ 70$handle=
opendir(
$path); 71if(
$handle){ 72while(
false!==(
$item=
readdir(
$handle))){ 73if(
$item!="."&&
$item!=".."
){ 74if(
is_dir(
$path.‘/‘.
$item)){ 75$this->delDirAndFile(
$path.‘/‘.
$item,
$delDir); 76}
else{ 77unlink(
$path.‘/‘.
$item); 78 } 79 } 80 } 81@
closedir(
$handle); 82if(
$delDir){
returnrmdir(
$path);} 83}
else{ 84if(
file_exists(
$path)){ 85returnunlink(
$path); 86}
else{ 87returnFALSE; 88 } 89 } 90 } 9192}
来源: http://www.bubuko.com/infodetail-2040929.html