PHP Tip #5: header
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.







Leave a comment