简体   繁体   中英

Able to Echo before header()

Came across something strange while migrating to my new server.

I have a script that will redirect users to another web page based on certain conditions. What I was doing, however, is echoing out 'Redirecting...', then using the header() function to actually redirect. Here is how the code looked:

if( $condition ) {
    echo 'Redirecting...';
    header( 'Location: ' . $url );
}

Now I only noticed that this is incorrect after switching over to our new server, tested it out, and saw that it would NOT redirect just output Redirecting... and once I searched about it, learned you cannot have any kind of output (unless using ob_start etc) before using the header() function.

Question is, why is this code, that should NOT work in ANY PHP installation, work on my old server? It will redirect with the echo before header() no problem.

Thanks!

You may have had output buffering on on the old server: output buffering will not output anything until the script finishes running. That allows it to get the header out before the actual output (as it knows the headers should be sent first).

If that makes sense.

Maybe your old installation had output_buffering defined to true in the php.ini. This delayed the output allowing you to set the headers even after echoing.

You must have had buffering turned on, even though you did not actively do so yourself. output_buffering = On in php.ini?

它在您的旧服务器上运行,因为默认情况下输出缓冲,由php.ini设置。

The old server probably had output buffering enabled by default. This meant that it wouldn't echo right away, but rather wait until the whole script has finished, and then echo . This also means that the header would be sent before the echo (since it was buffered), and therefore would not result in a warning.

On the new server, you most likely do not have output buffering enabled by default, and this would mean that it would echo straight away, without buffering it, and therefore it would be sent before the headers and result in a warning.

I would encourage you to use headers_sent() to check if the headers has been sent before using headers() after echo , like this:

<?php
echo "Foobar\n";
if(!headers_sent())
  header('Location: /helloworld.php');
?>

Related links:

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