简体   繁体   English

强制文件下载处理

[英]force file download handling

I am trying to understand how the response is created for force downloads and how the browser handles it.我试图了解如何为强制下载创建响应以及浏览器如何处理它。

Following this article here: tutorial .在本文之后: 教程

I have a script that sends a file as response to download.我有一个脚本,它发送一个文件作为对下载的响应。

<?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);

When the sleep() function is inside the loop, it waits for sometime before the file starts downloading.sleep() function 在循环内时,它会在文件开始下载之前等待一段时间。

But when placed outside the loop, file starts downloading immediately.但是当放置在循环之外时,文件会立即开始下载。

Can anyone please help me understand this behaviour?谁能帮我理解这种行为?

The problem in the second case is you send the file to the client before you call the sleep function.第二种情况的问题是您在调用睡眠 function 之前将文件发送到客户端。 You can store the output in an internal buffer and send it after the sleep function.您可以将 output 存储在内部缓冲区中,并在睡眠 function 后发送。 (I don't recommend this for production use.) Try this modified program: (我不建议将此用于生产用途。)试试这个修改后的程序:

<?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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM