Header Location Redirect Not Working in PHP?
Ran into a bug this evening when I was trying to redirect to a different page in PHP. I was trying to do the following:
if(blah blah blah) {
echo "some text here";
header("Location: http://www.example.com/");
}
The problem was that it wasn’t doing anything, even when the if condition was satisfied. It was printing out what ever I was echoing, but wasn’t redirecting.
Finally found out the problem after a bit of tinkering. In fact, it’s something I’ve learned a few times already in the past but keep forgetting.
If you read the documentation for header() carefully, you’ll find that it says:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
This means that your header has to be executed before ANY output from the PHP file hits the browser. In my case, I was echoing “some text here” to the browser before trying to execute the header function, causing the redirect not to work.
Removing the echo will fix the problem. Some people come across this problem in an even more annoying case, where they’re not even echoing anything. For example, if you copy and paste the following into a PHP file, it will not work:
<?php
header("Location: http://www.example.com/");
?>
Why won’t it work, even though you’re not echoing anything? Because there’s a single space before the <?php declaration. Annoying huh?
Hopefully you’ll read this warning before you ever run into this problem and tear out your hair.

