Php 在foreach循环问题中下载多个文件
我有以下代码通过代码下载一些日志文件Php 在foreach循环问题中下载多个文件,php,Php,我有以下代码通过代码下载一些日志文件 $files = array( '../tmp/logs/debug.log', '../tmp/logs/error.log'); foreach($files as $file) { header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Conten
$files = array( '../tmp/logs/debug.log',
'../tmp/logs/error.log');
foreach($files as $file) {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: text/html");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
但只下载数组的第一个元素。在本例中,如果交换元素,则仅交换error.log。有什么帮助吗?标题在同一执行过程中设置一次。如果放入循环,则下一个标头将不会发送。您可以使用javascript进行循环并使用ajax进行调用,但用户将一次获得多个下载,因此它会使浏览器和可用性崩溃。每个HTTP请求只能下载一个文件。实际上,一旦发送了第一个文件,浏览器将假定处理结束,并停止与服务器通信
如果要确保用户下载多个文件,一种解决方案可能是在服务器端动态地将它们全部压缩,然后将压缩文件发送给用户下载。您不能一次下载多个文件。HTTP协议设计为每个请求发送一个文件 或者,您可以压缩所有日志文件并将其作为压缩文件下载 您可以使用该类创建ZIP文件并将其流式传输到客户端。比如:
$files = array(
'../tmp/logs/debug.log',
'../tmp/logs/error.log'
);
$zipname = 'logs.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);