我试图了解如何为强制下载创建响应以及浏览器如何处理。
在此之后: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()
函数在循环内部时,它将等待一段时间才能开始下载文件。
但是当放置在循环之外时,文件立即开始下载。
任何人都可以帮助我了解这种行为吗?
第二种情况下的问题是您在调用睡眠功能之前将文件发送给客户端。您可以将输出存储在内部缓冲区中,然后在休眠功能后发送给它。
<?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;