php ZipArchive 文件压缩下载,多级文件夹压缩为指定文件夹

上节用到文件下载

https://www.cnblogs.com/chaihy/p/11028880.html

同理下载文件压缩下载

<a herf="/upload?filename=''/upload/file/zip&new_filename=''bb">文件下载</a>

参数new_filename 为zip名称

参数filename 为要压缩文件夹(多级文件夹/upload/file/zip/)

首先先检验要压缩文件夹是否存在 ,不然真的不存在会报错的

if(file_exists($filename)){

//得到zip地址

$zip_file = $filename.'/'.$new_filename.'zip';

//判断存在zip直接下载,不存在再压缩

if(!file_exists($zip_file)){

$zip = new ZipArchive();

if($zip->open($zip_file,\ZipArchive::CREAT)==true){

$this->addFileToZip($filename,$zip);

$zip->close();

}

}

//下载

 header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: " . filesize($zip_file));
header("Content-Disposition: attachment; filename=\"" . basename($zip_file) . "\"");
readfile($zip_file);

}

//压缩打包

function addFileToZip(){

$handler=opendir($path); //打开当前文件夹由$path指定。

while(($filename=readdir($handler))!==false){

https://php.net/manual/zh/ziparchive.addfile.php  查看addFile函数


}


}


}


@closedir($path);

}

以上如有不懂请加群,如有疑问请留言