【问题标题】:force file download handling强制文件下载处理
【发布时间】:2020-05-19 17:15:09
【问题描述】:

我试图了解如何为强制下载创建响应以及浏览器如何处理它。

在此处关注本文:tutorial

我有一个脚本,它发送一个文件作为下载响应。

<?php
// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');

// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
    echo str_repeat(".",1000);

    // sleep to slow down the download
    // sleep(5);
}
sleep(5);

sleep() 函数在循环中时,它会在文件开始下载之前等待一段时间。

但是当放置在循环之外时,文件会立即开始下载。

谁能帮我理解这种行为?

【问题讨论】:

  • 在它的每次迭代中挂起,在它的等待之外。两者都是无用的,不会在实际代码中使用
  • @LawrenceCherone 是的.. 这只是一个虚拟脚本.. 如文章中所述。
  • 如果你在睡眠后写这个$a=1会发生什么(在第二种情况下)。我的猜测是 php 看到没有剩余的输出来缓冲,它立即刷新..但我不确定
  • @Viney 文件会立即下载。可能是输出缓冲区的问题吗?
  • 你的睡眠不会像你认为的那样。你为什么要像你所说的那样“减慢下载速度”?

标签: php http-headers sleep


【解决方案1】:

第二种情况的问题是您在调用 sleep 函数之前将文件发送到客户端。 您可以将输出存储在内部缓冲区中,并在睡眠功能后发送。 (我不建议将此用于生产用途。) 试试这个修改后的程序:

<?php
// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');

//Turn on output buffering
ob_start();

// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
    echo str_repeat(".",1000);

    // sleep to slow down the download
    // sleep(5);
}

//Store the contents of the output buffer
$buffer = ob_get_contents();
// Clean the output buffer and turn off output buffering
ob_end_clean();

sleep(5);

echo $buffer;

【讨论】:

  • @Andrais.. 所以第一个echo 中的第一个iteration 立即开始输出到浏览器并忽略进一步的迭代??
  • 我谈到了第二种情况,睡眠函数放置在 for 循环之外,整个文件在睡眠函数之前发送,但是是的,除非你使用输出缓冲,否则它将开始输出。您可以在终端中尝试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 2013-06-20
  • 2013-01-27
  • 1970-01-01
相关资源
最近更新 更多