Home > Tutorials > PHP > PHP Tip #5: header
Permalink to PHP Tip #5: header

PHP Tip #5: header

by on 04.02.2009 | no comments

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. [...]

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:

if($error == true) {
  header('Location: /path/to/error/page');
}

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:

header("HTTP/1.0 404 Not Found");
header("Status: 404 Not Found");

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:

header("HTTP/1.0 404 Not Found");
header("Status: 404 Not Found");
echo '404';

Where as this will not work:

echo '404';
header("HTTP/1.0 404 Not Found");
header("Status: 404 Not Found");

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

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required