PHP 用 ZipArchive 打包指定文件到zip供用户下载

时间:2023-03-09 19:12:03
PHP 用 ZipArchive 打包指定文件到zip供用户下载
Ubuntu需安装zlib
sudo apt-get install ruby
sudo apt-get install zlib1g zlib1g.dev
Windows需开启php_zip.dll
如果在 "...\php\ext\" 没有这个文件,可以到网上下载一个
然后修改 "...\php\php.ini" ,找到 "extension=php_zip.dll"  去掉  ";",如果没有这行就加上。
$filename = "xxxx.zip";
ob_end_clean();
$zip = new ZipArchive();
$zip->open($filename, ZipArchive::OVERWRITE);
while (xxxx)
{
if(strlen($row->team_upload) != 0)
{
$sitelen = strlen($row->team_upload);
$attachfile = xxxx//写绝对径,建议用PHP环境变量
$attachfile=iconv("UTF-8","GBK",$attachfile); //转码,打包中文文档
$zip->addFile( $attachfile , basename($attachfile)); //把文件放入zip
}
}
$zip->close();//关闭
header('Content-Description: File Transfer');
Header("content-type:application/x-zip-compressed");
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean(); //清空但不关闭输出缓存
flush();
@readfile($filename);
@unlink($filename);//删除打包的临时zip文件。文件会在用户下载完成后被删除