PHP echo before setting content type header?
我有以下PHP代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function download_file($file, $description=null, $filename=false){ $filename = $filename || basename($file); ob_start(); if(is_string($description)){ $description = preg_replace("/\$1/", $filename, $description); echo $description; } sleep(2); header('Content-Type: '.$this->file_mimetype($file)); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename="" . basename($file) ."""); readfile($file); header("Content-Type: text/html"); ob_end_flush(); } download_file("https://raw.githubusercontent.com/Gethis/ED/master/easydevop.class.php","Downloading easydevop.class.php"); |
问题是,它在下载之前没有回响"downloading easydevop.class.php"。我也试着在所有的头球后回音,但也没用。拜托,有什么帮助吗?
如你所见,我确实使用了
不能同时使用"echo"(显示HTML内容)和发送文件给用户。您可以先显示HTML页面,然后使用将用户重定向到文件HTML重定向
1 | <META HTTP-EQUIV="REFRESH" CONTENT="0;URL=http://url.to/file/or_script/that_send_file/"> |
或者javascript重定向如何使用javascript重定向?
正如我之前提到的,下载文件时不能显示echo。当你下载文件时,你只需下载文件,就可以了。
但是,使用javascript,您可以在开始下载之前显示消息。下面是测试脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?php if (isset($_GET['id'])) { $file = 'testfile.txt'; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); readfile($file); exit; } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body> <script type="text/javascript"> function showDownload(message) { document.getElementById("hidden").innerHTML = message; document.getElementById("link1").style.display = 'none'; // you can even hide download link if you want } Download </body> </html> |