PHP Tip #5: header

/ PHP / by Paul Robinson / 0 comments
This post was published back on April 2, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Another useful command that all PHP coders should know is the header() function. You can use it to send a HTTP header to the server.

As an example you could use it to redirect to a certain webpage if a certain string of conditions are true, just like this:

You can also use it to send a 404 header. This is useful when using an index.php file as a URL router, similar to PHP frameworks like Codeigniter, if a file isn’t found you could get the index.php file to send a 404 header & then include a pre-made 404 page. Something like this always works for me:

There is one massively important thing to remember. You can only use the header() function before you have output anything to the browser. For example the following will work:

Where as this will not work:

I hope that helps those who are unfamiliar with the header() function. 🙂

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more