PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载
PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有疑问欢迎交流。这里整理一下常用的示例供参考。
一、几行代码实现PHP文件打包下载zip
<?php
/**
* 没有写成class 或者 function ,需要的朋友自己写,就这么几行。。
*/
$filename = "./test/test.zip"; //最终生成的文件名(含路径)
if(!file_exists($filename)){
//重新生成文件
$zip = new ZipArchive();//使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit('无法打开文件,或者文件创建失败');
}
foreach( $datalist as $val){
$attachfile = $attachmentDir . $val['filepath']; //获取原始文件路径
if(file_exists($attachfile)){
$zip->addFile( $attachfile , basename($attachfile));//第二个参数是放在压缩包中的文件名称,如果文件可能会有重复,就需要注意一下
}
}
$zip->close();//关闭
}
if(!file_exists($filename)){
exit("无法找到文件"); //即使创建,仍有可能失败。。。。
}
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename)); //文件名
header("Content-Type: application/zip"); //zip格式的
header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
header('Content-Length: '. filesize($filename)); //告诉浏览器,文件大小
@readfile($filename);
?>