Creating A 404 Page In PHP

Setting up a 404 page on your site will help users when they navigate to a page that doesn't exist. Rather than dropping them into a scary server message you can give them a nice friendly error page. The first step is to make sure that if the user generates a 404 error they are given a nice page. Add this line to your .htaccess file.

ErrorDocument 404 404.html

Now when a user hits a non existent page they will see you nice error page. However, you sometimes will want to produce a 404 page when the server doesn't give out a 404 error, for example, if you have the following URL.

If the id of 123 didn't exist then the page would still show something, and the server wouldn't give a 404 error as the page does, in fact, exist. You will therefore need to be clever in your script so that if the id exists you return a normal header, and if it doesn't you return a 404 header. To produce a 404 header from a PHP script you need to use the header() function in the following way.

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

So to integrate this into the rest of the site you would do something like this. The function idExists would be a call to a database or something that checks to see that the id is present on the system.

if ( idExists($_GET['id'] ) {
 // run normal page function
 header("HTTP/1.0 404 Not Found");
 // print off page with not found information

Make sure you put the header() function above any echo or print statements or you will produce an error message.


thanks for sharing the valuable information , i am a website desginer and developer in noida, your article help me a lot, thanks


Add new comment

The content of this field is kept private and will not be shown publicly.
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.