Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 599
Bill Haynek Avatar asked Aug 26 '10 13:08

Bill Haynek


1 Answers

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.

like image 131
Narcissus Avatar answered Oct 22 '22 18:10

Narcissus