PHP提供了ZipArchive
类,可以实现指定文件打包,并下载的功能。
可是,当文件比较多比较大的时候,打包需要很长时间处理,这样就需要用户等待,体验不是很好。
这时候,我们可以使用管道机制,不生成压缩包,而是一边压缩一边下载。这个功能需要用到popen
函数和zip
命令。
使用 popen
函数和zip
命令,实现Zip内存打包下载。
<?php function action_index() { $files = glob("D:\BaiduNetdiskDownload\ApwWnmp2021.6-原始软件列表\php\*"); header('Pragma: no-cache'); header('Content-Description: File Download'); header('Content-disposition: attachment; filename="myZip.zip"'); header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); //Opening a zip stream $files = implode(" ", $files); if ($files){ $fp = popen('zip -q -r -0 -j - ' . $files, 'r'); } $index = 0; while(!feof($fp)) { echo fread($fp, 8192); $index++; if ($index % 1024 == 0){ ob_flush(); flush(); } } //Closing the stream if ($files){ pclose($fp); } }
zip
命令不支持该功能。
ZipArchive
是可以自定义目录和文件名的,这时我们应该如何处理呢?