Creating A 404 Page In PHP

2nd April 2008 - 2 minutes read time

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.

http://www.example.com/index.php?id=123

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.

  1. if ( idExists($_GET['id'] ) {
  2. // run normal page function
  3. }else{
  4. header("HTTP/1.0 404 Not Found");
  5. // print off page with not found information
  6. }

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

Comments

Permalink

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

Evermolpro (Thu, 05/06/2021 - 15:55)

Add new comment

The content of this field is kept private and will not be shown publicly.