简体   繁体   中英

How to Stop Header, so I can echo to screen from the same function (PHP)

I'm finding Headers a nightmare to get my head around, I have a file the user downloads which works fine. However I then whish to echo to the screen that xx file has been sent; but ofc this echo is just placed inside the sent file.

Full dowload code is as follows:

    function download()
{
$orderNo = $_POST['orderNo'];
$lines = file('F:/xamptest/htdocs/UniProject/upload/Amazon output.txt');
$lineCount = count($lines);
if($orderNo>0&&$orderNo<=$lineCount)
{
    $lineEx = explode("\t", $lines[($orderNo-1)]);      
    $file = fopen('Order.txt', 'w');
fwrite($file, $lineEx[8].PHP_EOL .$lineEx[17].PHP_EOL .$lineEx[18].PHP_EOL  .$lineEx[19].PHP_EOL  .$lineEx[20].PHP_EOL  .$lineEx[21].PHP_EOL  .$lineEx[22].PHP_EOL  .$lineEx[23].PHP_EOL);
fclose($file);
$file = 'Order.txt';

ob_end_clean();
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
echo "Current order, number: ".$orderNo."<br> Has been downloaded";
}
else
{
echo "Please enter a valid Order Number between 1 and ".$lineCount;
}
}

I can't seem to find how to stop the headers without using exit(); which then still means it won't show the echo, and any more use of ob_end_clean(); in any other ways causes the sent file to be empty. Only other thing I could think was having the echo in its own function, but as it runs at the same time the headers do it still places it in the file.

Many thanks for any help - Tom.

What you're dealing with is an HTTP request . The browser requests a URL with an HTTP request, the server sends a response . Click a link → browser sends request → server sends HTML page in response. Use Chrome, Safari or Firefox + Firebug and play around with the Network tab in their Web Inspector/development tools to get a real feeling for what's happening.

If you want to download a file, it works the same way. Only the server tells the browser through HTTP headers that this response is not an ordinary HTML page, but is supposed to be a file which it should save on disk.

As you should be able to see, there's no way to respond with a file download and an HTML page at the same time in one response. There's simply no way to do it. You have to output your HTML page with the message first, then link to the file download from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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