我有以下PHP代码:
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");
问题是它在下载之前没有回复“下载easydevop.class.php”。我也尝试在所有标题之后回显它,但这也不起作用。请帮忙吗?
如您所见,我确实使用了ob_start()
和ob_end_flush()
答案 0 :(得分:1)
你不能使用" echo" (显示HTML内容)并同时向用户发送文件。 您可以先显示HTML页面,然后使用将用户重定向到该文件 HTML重定向
<META HTTP-EQUIV="REFRESH" CONTENT="0;URL=http://url.to/file/or_script/that_send_file/">
或javascript重定向How do I redirect with Javascript?
答案 1 :(得分:0)
正如我已经提到的,下载文件时无法显示回显。下载文件时,您只需下载文件即可。
但是,使用JavaScript可以在开始下载之前显示消息。这是测试脚本:
<?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
}
</script>
<div id="hidden"></div>
<a href="download.php?id=1" onclick="showDownload('You are downloading file id = 1'); return true;" id="link1">Download</a>
</body>
</html>