设为首页 加入收藏

TOP

PHP使用ZipArchive批量打包压缩文件并下载
2023-07-23 13:26:14 】 浏览:61
Tags:PHP 使用 ZipArchive 包压缩 文件并

PHP使用ZipArchive批量打包压缩文件,并下载。使用php自带的ZipArchive类,可以压缩或解压文件。

首先需要确定已经安装了zip扩展,如果没有安装,请先安装,下载:http://pecl.php.net/package/zip (相应php版本的zip包)

 

 

先把需要下载的文件路径找出来并组成数组,如下

Array
(
    [0] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\aa.pdf
    [1] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\bb.pdf
    [2] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\cc.pdf
    [3] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\dd.pdf
    [4] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\ee.pdf
    [5] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\ff.pdf
    [6] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\gg.pdf
)

逻辑:先把文件压缩到指定目录(自定义$addonFile目录下),然后再把文件输出下载

代码如下:

$files = ('E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\aa.pdf','E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\bb.pdf','E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\cc.pdf','E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\dd.pdf');

// 压缩文件名
$addonFile = ROOT_PATH.'public'.DS.'uploads'.DS.'downzip'.DS.'学科评估_【'.$info['hospital'].'_'.$this->year. '年】.zip';
$zip = new \ZipArchive;

//新建zip压缩包
$zip->open($addonFile,\ZipArchive::CREATE | \ZipArchive::OVERWRITE);
//把文件一张一张加进去压缩
foreach ($files as $key => $value) {
    $zip->addFile($value,basename($value));
}
//打包zip
$zip->close();

header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header('Content-disposition: attachment; filename='.basename($addonFile)); //文件名 
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($addonFile)); //告诉浏览器,文件大小 
readfile($addonFile);

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇浅谈PHP设计模式的中介者模式 下一篇【踩坑日记】nginx server_name配..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目