Header Error in PHP
It has been brought to my attention a simple error that people tend to come across when writing a PHP script that contains headers. It’s a tidious error, because you might not be pinpointed in the right direction, meaning, it will not tell you what the error is exactly. I have concluded that many people do not want to spend about five minutes to read how to work with headers in PHP, so I decided to write about this and try to explain in the simplest form I can.
Headers in PHP
All cases I have personally seen, tend to end up with the same answer, which is, ‘DO NOT OUTPUT ANYTHING BEFORE YOUR PHP SCRIPT’. This should be taken into consideration when having headers in your script.
We all know how to create headers, but just in case you don’t here’s a simple example:
That’s it. I highly recommend when creating headers to redirect a user, to use the exit right after. This avoids all other script to be excecuted.
Where are the errors?
The errors that are encountered are usually due to poor programming practices. To all fellow PHP’er, I highly recommend to have all your PHP script above the HTML tag. For example, if you are logging in a user, there is no reason to have your script right after your body tag, or even any tag for that matter. When entering such a restricted site, the first thing a script should do is check if it is an authorized user, and if not, then use the code above to redirect to a proper login page.
Now the error resides in the following:
Note the arrows in the first screenshot. This indicate poor programming habits when writing headers in PHP. There should not be no output at all before headers. In the second screenshot, please note that the arrow is pointing to a whitespace. Yes, whitespaces are also included, and cause you headaches when trying to find that problem.
All PHP’er should grab the habit of making your scripts above anything whatsoever. Your code should be organized, easy to read, and direct to the point.