PHP echo before setting content type header?

I have the following PHP code:

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

The problem is that it is not echoing "Downloading easydevop.class.php" before the download. I also tried echoing it after all the headers, but that didn't work either. Please, any help?

As you can see I did use ob_start() and ob_end_flush()


You can't use "echo" (showing HTML-content) and send file to user at the same time. You can show HTML-page first, and then redirect user to the file, using HTML-redirect

<META HTTP-EQUIV="REFRESH" CONTENT="0;URL=http://url.to/file/or_script/that_send_file/">

or javascript redirect How do I redirect with Javascript?


As I already mentioned you cannot display echo when downloading file. When you download file you can just download file, nothing more.

However using JavaScript you can display message before starting downloading. Here is the test script:

<?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>
链接地址: http://www.djcxy.com/p/34736.html

上一篇: JS window.location不工作

下一篇: PHP在设置内容类型头之前回显?