且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用php将多个文件下载为zip文件

更新时间:2022-12-27 08:32:52

您可以使用

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

并进行流式传输:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

第二行强制浏览器向用户显示一个下载框,并提示名称filename.zip.第三行是可选的,但某些(主要是较旧的)浏览器在某些情况下会出现问题,而未指定内容大小.

The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.