Possibility of an echo before the heading ()

There was something strange going to the new server.

I have a script that redirects users to another web page based on certain conditions. However, what I did repeats "Redirecting ..." and then uses the header () function to actually redirect. This is what the code looked like:

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

Now I just noticed that this is not right after switching to our new server, tested it and saw that it does NOT redirect only output redirection ... and as soon as I searched about it, I found out that you cannot have any (other than using ob_start, etc.) before using the header () function.

The question is why this code, which should NOT work in ANY PHP installation, works on my old server? It will redirect with an echo before the header () without any problems.

Thanks!

+7
redirect php header
source share
5 answers

You may have output buffering on the old server: output buffering does not output anything until the script finishes working. This allows you to get the header before the actual output (since it knows that headers should be sent first).

If that makes sense.

+9
source share

Perhaps your old setup had output_buffering defined as true in php.ini. This delays the output, allowing you to set headers even after an echo.

+4
source share

You must have turned on buffering, although you yourself did not do this actively. output_buffering = On in php.ini?

+3
source share

It worked on your old server since by default you had output buffering set by php.ini.

+1
source share

The old server probably had output buffering enabled by default. This meant that it would not be echo right away, but rather wait for the entire script to finish, and then echo . This also means that the header will be sent before echo (since it was buffered) and therefore will not result in a warning.

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

I would advise you to use headers_sent() to check if headers were sent before using headers() after echo , for example:

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

Related links:

0
source share

All Articles