强制文件下载处理

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


在此处关注本文:教程。


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


<?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()函数在循环内时,它会在文件开始下载之前等待一段时间。


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


谁能帮我理解这种行为?


摇曳的蔷薇
浏览 57回答 1
1回答

扬帆大鱼

第二种情况的问题是在调用睡眠函数之前将文件发送给客户端。您可以将输出存储在内部缓冲区中,并在睡眠功能之后发送。(我不建议将其用于生产。)试试这个修改后的程序:<?php// it's a zip fileheader('Content-Type: application/zip');// 1 million bytes (about 1megabyte)header('Content-Length: 1000000');// load a download dialogue, and save it as download.zipheader('Content-Disposition: attachment; filename="download.zip"');//Turn on output bufferingob_start();// 1000 times 1000 bytes of datafor ($i = 0; $i < 1000; $i++) {&nbsp; &nbsp; echo str_repeat(".",1000);&nbsp; &nbsp; // sleep to slow down the download&nbsp; &nbsp; // sleep(5);}//Store the contents of the output buffer$buffer = ob_get_contents();// Clean the output buffer and turn off output bufferingob_end_clean();sleep(5);echo $buffer;
打开App,查看更多内容
随时随地看视频慕课网APP