December 24, 2011 learn_php

Header Error in PHP

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.

My advice

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.

3 thoughts on “Header Error in PHP

  1. Hello,
    if i wouldn’t like to use ob_flush and i using include to simple page in main page that simple page has header after submit form to same simple page error found in some hosting only i would like to get other solution by php code
    not in php.ini like buffer off>on .not send header to another page
    example:
    Main page
    ……

    simple page not contain html that abstract

Leave a Reply

Your email address will not be published. Required fields are marked *

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.