views:

52

answers:

5

Hi,

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!

A: 

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

Ashley
Thanks! I appreciate it!
Bill Haynek
+1  A: 

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.

Stefano Borini
Thanks! I appreciate it!
Bill Haynek
+5  A: 

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.

Narcissus
Thank you! that seems to be the problem just checked php.ini on old server and output_buffering is set to 4096 so it was on :)
Bill Haynek
+1  A: 

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

mwittrock
Thanks! I appreciate it!
Bill Haynek
A: 

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:

Frxstrem
Thank for the help I appreciate it :)
Bill Haynek