为每个循环问题下载多个文件


Download multiple files inside foreach loop issue

我有以下代码通过代码下载一些日志文件

$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);
    }

但只下载数组的第一个元素。在这种情况下,调试.log,如果我交换元素,则只有错误.log。请帮忙吗?

每个 HTTP 请求只能下载一个文件。实际上,一旦发送了第一个文件,浏览器就会认为这是处理的结束,并停止与服务器通信。

如果要确保用户下载多个文件,一种解决方案可能是在服务器端即时压缩所有文件,然后将 zip 文件发送给用户进行下载。

不能一次下载多个文件。HTTP 协议旨在为每个请求发送一个文件

或者,您可以压缩所有日志文件并将其下载为 zip 文件。

可以使用 ZipArchive 类创建 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);
标头在同一

次执行中设置一次。如果放入循环,则不会发送下一个标头。你可以在javascript中进行循环并使用ajax调用,但是用户将一次获得多个下载,因此它可能会使浏览器和可用性崩溃。