404/403 Server Error Pages

404/403 Website Error Pages With PHP Auto-Mailer

Apr 17th in PHP by Jarel Remick

Website error pages are perhaps one of the most overlooked pieces of a fully rounded website. Not only are they important but they give you the opportunity to have a little fun. Although many web developers rely on server logs to keep an eye out for hits on error pages, I'm going to take a different approach by using a PHP generated email. In addition, we will spice up the design a bit, add basic navigation and link to the website sitemap.

PG

Author: Jarel Remick

I'm a freelance designer and web developer, an author and reviewer at ThemeForest.net, a writer for the ThemeForest blog and occasionally web.appstorm.net. When I actually manage to get away from the computer, I'm hiking, watching movies or spending time with my girlfriend in sunny Las Vegas. – View my net.tutsplus.com posts here.

About Error Pages

404 Not Found

The most common error page - the one in which you are most likely to be familiar with - is the "404 Not Found page". More people encounter this type of error page than any other. Other common error messages you may have come across are 500 Internal Server Error, 400 Bad Request or 403 Forbidden. Wondering what the number is for? It simply refers to the HTTP code.

404 Not Found

Default error pages are quite boring (as you can see above) and offer no purpose to visitors other than letting them know some boring error happened. For these reasons, it is a great idea to provide custom pages for the most common errors encountered. This tutorial will only cover two: the "404 Not Found" and "403 Forbidden".

Check for custom error page support

First, check to make sure your hosting provider allows you to use your own error pages. Almost all of them do, and most of them even provide a configuration area within your control panel to help you quickly create the pages. In this tutorial we will configure an Apache web server (the most common). This is easier than you might think.

Configure .htaccess

Next, connect to your server via FTP or control panel and navigate to the document root directory (usually www or public_html) which contains your website files. We will be looking for the .htaccess file. It is sometimes hidden so make sure you are viewing all files including hidden ones. If your server doesn't have one, you can create one using any text editor. Make sure to make a backup of the .htaccess file if your server already has one.

Add the following lines to your .htaccess file:

ErrorDocument 404 /error/404.php
ErrorDocument 403 /error/403.php

The first half (ErrorDocument 404) is telling the server we are going to define the location of the 404 error document. The second half defines the actual location of the error document. In this case we will put it in the "error" directory and call them 404.php and 403.php, respectively.

Now save the .htaccess file and upload it to the document root directory.

Design the Custom Error Pages

It is best to stay with the same design as your website already uses so that you don't confuse your visitors and risk losing them. You should also include helpful elements such as a polite error message, suggested links, a search feature, or a link to your sitemap. These features will depend on the level of content your website provides and what you feel will be most helpful.

Envato Marketplace 404 Page

As you can see below, the 404 Not Found page for Nettuts+ has stated the error and emphasized the search feature by including it in the body beneath the error message. You could take this a step further by including a short list of links to possible pages which might encourage the visitor to continue exploring more of the site (keep it simple and short though) -or even a humorous image (every one likes laughing right?). For small websites it may be a good idea to include a visible sitemap as well.

Page Not Found

Here is something I put together for this tutorial that you can use for your website as well (included in the download above). It's very simple so you will be able to put the content of it directly into your existing website template. As you can see, I attempted to include a little bit of a humorous element while also stating the error politely and including some options to help the visitor either find what they were looking for or continue browsing the website.

404 Not Found

You'll notice it does not specify the HTTP error code in the body of the page. Instead I chose to only use the error code in the title of the page. The reason for this is to keep things as simple and user friendly as possible. Most people don't care what 404 or 403 means, they want to know what's going on in plain English. For people who want the error code, it is still available via the title.

If you want to see some really great 404 designs visit:

  • http://www.smashingmagazine.com/2009/01/29/404-error-pages-reloaded-2/
  • http://www.smashingmagazine.com/2007/08/17/404-error-pages-reloaded/
  • http://www.smashingmagazine.com/2007/07/25/wanted-your-404-error-pages/
  • http://blogof.francescomugnai.com/2008/08/the-100-most-funny-and-unusual-404-error-pages/

The Auto-Mailer PHP and Why We Will Use Email Notification

This is the part of the tutorial in which some web guru's might argue with. You can use your web server's logs to check for error pages and much, much more. Why do I choose email notifications?

  1. I don't want to log into my server every day and dig through all that extra information.
  2. I am available by email almost literally all day, the fastest way to reach me is email (or twitter). With this in mind, I want to know about 404 and 403 errors fairly quick so email is best.
  3. An increasing number of people are starting websites, while most of those people know almost nothing about web hosting let alone server logs. These people will only be running small sites; so email is ideal.
  4. Being notified right away allows me to quickly take action if a website of mine is being "harvested" (ThemeForest templates), if someone is attempting to access something restricted repeatedly or if I have a broken link somewhere.

So with all that said, let's get on with the code shall we!

The Code

First, we will create a file named error-mailer.php which will be used to collect information about our visitor and send the email. Once you have created the file we will start by specifying our email and email settings.

<?php

# The email address to send to
	$to_email = 'YOUR-EMAIL@DOMAIN.com';

# The subject of the email, currently set as 404 Not Found Error or 403 Forbidden Error
	$email_subject = $error_code.' Error';

# The email address you want the error to appear from
	$from_email = 'FROM-EMAIL@DOMAIN.COM';

# Who or where you want the error to appear from
	$from_name = 'YourDomainName.com';
Then we will collect information about our visitor such as IP address, requested URI, User Agent, etc. The following code will collect that information.
# Gather visitor information
    $ip = getenv ("REMOTE_ADDR");                // IP Address
    $server_name = getenv ("SERVER_NAME");       // Server Name
    $request_uri = getenv ("REQUEST_URI");       // Requested URI
    $http_ref = getenv ("HTTP_REFERER");         // HTTP Referer
    $http_agent = getenv ("HTTP_USER_AGENT");    // User Agent
    $error_date = date("D M j Y g:i:s a T");     // Error Date
Now we will write the script to email the information to us with the details specified earlier.
# Send the email notification
require_once('phpMailer/class.phpmailer.php');
    $mail = new PHPMailer();

    $mail->From = $from_email;
    $mail->FromName = $from_name;
    $mail->Subject = $email_subject;
    $mail->AddAddress($to_email);
    $mail->Body =
    "There was a ".$error_code." error on the ".$server_name." domain".
    "\n\nDetails\n----------------------------------------------------------------------".
    "\nWhen: ".$error_date.
    "\n(Who) IP Address: ".$ip.
    "\n(What) Tried to Access: http://".$server_name.$request_uri.
    "\n(From where) HTTP Referer: ".$http_ref.
    "\n\nUser Agent: ".$http_agent;

    $mail->Send();

?>

We are using the phpMailer class to do this as demonstrated by Jeffrey via the ThemeForest blog to create a nice AJAX contact form. This version of the phpMailer class is for PHP 5/6 so if your server is running PHP 4 you will need to use the corresponding version by downloading it here.

404.php and 403.php Error Pages

The last thing we need to do is customize the error pages we designed earlier by sending the proper headers and set the $error_code variable by inserting the following code at the beginning of each page respectively (separated by -------).

<
<?php 

header("HTTP/1.0 404 Not Found");
$error_code = '404 Not Found';		// Specify the error code
require_once('error-mailer.php');	// Include the error mailer script

?>
-------
<?php 

header("HTTP/1.0 403 Forbidden");
$error_code = '403 Forbidden';		// Specify the error code
require_once('error-mailer.php');	// Include the error mailer script

?>

What we are doing here first is setting the correct HTTP header to return 404 Not Found and 403 Forbidden, respectively. When search engines accidentally land on this page we want to make sure they know what kind of page it is, instead of thinking that it's a normal web page named 404.php or 403.php.

Then we specify the error code to be used in the mailer script and include the mailer script so it can do its work. This way if we make a change to the mailer script, we only need to edit one file instead of two or more (if you setup additional custom error pages).

Conclusion

There you have it! Your own custom error pages that are search engine friendly, and let you know via email when you've had a visitor as well as all the information you will need to fix any problems. A few last things to consider:

  1. Internet Explorer requires error pages that are at least 512 byes in size (if you use the example files you'll be fine)
  2. High traffic websites have the potential to generate A LOT of emails so make sure you setup some sort of email filter for these error notifications so they don't flood your inbox. I use Gmail so I just have a label and filter setup for these emails.
  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Colin McFadden April 17th

    Great tutorial, man! Very helpful =)

    ( Reply )
  2. PG

    Saro April 17th

    Thanks :)

    ( Reply )
    1. PG

      ananasky May 29th

      this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
      copy of this lesson on my site herehttp://anan.135gb.com/vb/

      ( Reply )
  3. PG

    Ali April 17th

    thanks … very awesome :)

    ( Reply )
  4. PG

    BluE-=-FaLcOn April 17th

    THANKS DEAT

    ( Reply )
  5. PG

    Philo April 17th

    Already knew this! :P
    Great article though!! :)

    ( Reply )
    1. PG

      lawrence77 April 17th

      Then you miss to write a tutorial here! :(

      ( Reply )
      1. PG

        Philo April 17th

        True ;)
        But don’t worry, trying to get 2 exciting tutorials published this month!

      2. PG

        lawrence77 April 18th

        what are the tutorials?
        yup, You already write 3 tutorials! ;) I didn’t notice that before sending!

        Me too try to write tutorials…… :)

  6. PG

    Mukarram April 17th

    Nice article….keep it up more !!!

    ( Reply )
  7. PG

    rob j April 17th

    I like it!

    ( Reply )
  8. PG

    iPad April 17th

    I didn’t know we can achieve this! thanks!

    ( Reply )
  9. PG

    wayno007 April 17th

    Thanks, great article.

    ( Reply )
    1. PG

      yeahman May 4th

      yea man

      ( Reply )
  10. PG

    Bryan P. April 17th

    I have some clients which need error monitoring on their sites. It will allow me to keep track of errors that customers see and I dont. Thanks for the post.

    ( Reply )
  11. PG

    Sirwan April 17th

    @Jeff

    Personally, I don’t mind what tutorials you publish at nettuts, as long as there’s something new, regularly. I already knew about this, and most people probably did, but the fact that the pace of publication is increasing makes everyone here happy.

    I already knew about this, but I forgot about this, so Im glad this this article reminded me of it and how important error pages can be. Well done.

    ( Reply )
  12. PG

    Random Gemini April 17th

    Great article Jarel! You’re improving my blog by leaps and bounds every time you post!

    ( Reply )
  13. PG

    crysfel April 17th

    thanks you, this is really useful.

    thanks again :D

    ( Reply )
  14. PG

    Sam Granger April 17th

    I already use a similar method, except I have the info display in my admin dashboard instead of getting an email. :)

    Until now I’ve only had users typing in wrong links themselves though. I also make my 404 display pages with similar keywords found in the url that was requested.

    ( Reply )
  15. PG

    Neil April 17th

    .Net has much better 404/500 handling using a global.asax

    ( Reply )
    1. PG

      Shane April 19th

      The CustomErrors section of web.config vs. .htaccess…

      arguable…

      ( Reply )
  16. PG

    myDevWares April 17th

    Interesting, I was thinking of implementing the automail feature on the 404/403 pages of my website even before this tutorial even came out!

    I guess genius’s think alike! *wink*

    ( Reply )
  17. PG

    Taylor Satula April 17th

    Huh, Thanks Very Helpfull
    Good tut. No problems

    ( Reply )
  18. PG

    Craigsnedeker April 17th

    Already have a custom one :D But good tut none the less.

    http://snedekerdesignz.com/ss

    ( Reply )
  19. PG

    Joe April 17th

    Great! More user-friendly.

    ( Reply )
  20. PG

    Tony Virelli April 17th

    Don’t forget that on apache servers you need to set AllowOverride to All in the virtual hosts file, or you .htaccess won’t work.

    ( Reply )
  21. PG

    Will April 17th

    I don’t know why it doesn’t work properly…

    When I get the email the “(What) Tried to Access” is the link to the error404/403.php page and the “(From where) HTTP Referer” field is empty.

    What’s the problem?

    Thanks.

    ( Reply )
    1. PG

      Rae April 27th

      The most likely cause of that is that the user typed in the url directly. Thus, there is no referrer – it was a direct access.

      ( Reply )
  22. PG

    Matt Egan April 17th

    This is nice. I’m thinking about adding a page (the url) into a database every time it gets hit, then, when the same page gets hit again, it doesn’t e-mail me because that url is already in the database. (Or possibly just increment the hit count by 1 in the database every time it gets hit) If the hit count its higher than 2 then I don’t get an e-mail. I guess just so that I don’t get bombarded by a bunch of e-mails.

    ( Reply )
  23. PG

    Free CSS Templates April 17th

    Great tutorial. Should come in handy! I really like the design of the themeforest 404, much better than getting a blank white screen with some black writing.

    ( Reply )
  24. PG

    Mason Sklut April 17th

    Nice post Jarel!

    ( Reply )
  25. PG

    Rachel April 17th

    FYI… I attempted to add you to my Shrook RSS feed. I get an ‘XML not readable’ error message.

    ( Reply )
  26. PG

    Rachel April 17th

    Skip my last comment (and please don’t post it.) Worked when I used the RSS button in the url window.

    ( Reply )
  27. PG

    Rahul Chowdhury April 17th

    Thanks man, great tutorial, I needed this for the phpMail(), thanks for it.

    ( Reply )
  28. PG

    Ignas April 18th

    nice one ;)

    ( Reply )
  29. PG

    Lamin Barrow April 18th

    Very useful. Thanks so much. :D

    ( Reply )
  30. PG

    Saleh Galiwala April 19th

    Its very useful.I am a web devloper and really helped me.

    Thanks
    Saleh
    unimax.systems@gmail.com
    PHP /ASP /FLASH

    ( Reply )
  31. PG

    Jarel April 19th

    Thanks for the comments everyone! Much appreciated :-D

    ( Reply )
  32. PG

    Shane April 19th

    This sort of thing can be very revealing. You could think that users weren’t getting 403/404 errors. Set up this sort of thing and you’ll probably be surprised!

    ( Reply )
  33. PG

    Derek Herman April 19th

    I currently do this with my 404 but not my 403, maybe I will do an upgrade cause I like the added benefit. Also, if you use WordPress you can see what pages people are trying to access and ban them if they are doing weird stuff. I do that with a plugin called WP-BlockYou and send them to a banned message on a sub domain.

    ( Reply )
  34. PG

    David Singer April 19th

    Cool article. I like Swift Mailer better than auto mailer though… Same idea though.

    ( Reply )
  35. PG

    Ronald April 20th

    Is it possible to use this on a Microsoft IIS server, with php?

    ( Reply )
  36. PG

    Nick Brown April 20th

    This seems like one of those things that a lot of people forget to do but can make the difference of keeping or losing a visitor.

    ( Reply )
  37. PG

    Adrian April 20th

    Strange think using mails for 404 error. For a website with a large amount of traffic only think you get is: too many e-mails with same problem. Using the script as it is given in this article it`s not recommended.

    ( Reply )
  38. PG

    Martyn Web April 20th

    Very Helpful tutorial!

    I look forward to testing it out.

    Thanks

    ( Reply )
  39. PG

    rafaelrrp April 20th

    Thanks!!!!!

    ( Reply )
  40. PG

    Comedy Cluster April 20th

    My website’s having major problems with this…and I don’t know quite why. Maybe it’s just going to take some time for it to work its magic. Sometimes it takes a while for files to update on my host.

    ( Reply )
    1. PG

      Comedy Cluster April 21st

      Still hasn’t worked.
      This is what I get:

      Warning: require_once(phpMailer/class.phpmailer.php) [function.require-once]: failed to open stream: No such file or directory in /home/comedycl/public_html/error/error-mailer.php on line 25

      Fatal error: require_once() [function.require]: Failed opening required ‘phpMailer/class.phpmailer.php’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/comedycl/public_html/error/error-mailer.php on line 25

      Pleeease help!

      ( Reply )
  41. PG

    Phanor Coll April 21st

    hi, great article…but im having a problem trying it, i get this error:

    Could not instantiate mail function.

    and i have the same code as the article..

    ( Reply )
  42. PG

    Chukki April 21st

    I thought about something like that before, but not in such a good way. I only tracked the request url.

    Thanks for this wonderful article!

    ( Reply )
  43. PG

    yala7ob April 22nd

    this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
    copy of this lesson on my site here

    ( Reply )
  44. PG

    Ryan April 23rd

    Great read… This will be going up on my website! Thanks

    ( Reply )
  45. PG

    Mahbub April 26th

    I did make some sort of arrangement for 404 pages to email automatically in 2006. It’s a good way to keep your website clean and most of the spiders don’t like 404.

    ( Reply )
  46. PG

    www.fkra4all.co.cc April 29th

    hi and thanks for every thing

    ( Reply )
  47. PG

    Aria Rajasa May 12th

    Awesome! I miss this one.. will implement it right away

    ( Reply )
  48. PG

    mary May 12th

    Awesome!! This is going to be a great help for me!

    thanks :)

    ( Reply )
  49. PG

    koko May 15th

    Can I sent to two email?

    # The email address to send to
    $to_email = ‘email1′;

    how can I implement it?

    ( Reply )
  50. PG

    БAKИHEЦ May 23rd

    Эээ, а объясните, пожалуйста, а то я что то не совсем въехал в тему, это как?

    ( Reply )
  51. PG

    spoon5 May 27th

    Nice work, keep it up!!!

    ( Reply )
  52. PG

    Homeeg June 4th

    Nice work Keep it Up

    ( Reply )
  53. PG

    John June 13th

    Thanks for the tutorial, very handy.

    ( Reply )
  54. PG

    Ansar Ahmed June 16th

    Good, even i have implemented same in my previous company but how about having all the error(404,403,500) redirected to only one error.php and in the common error.php page we will handle in switch, basically pass the code via .htaccess error.php?code=404, error.php?code=403 etc.

    ( Reply )
  55. PG

    Michael June 18th

    If you were implementing this on a more trafficked site wouldn’t it make more sense to only send a notification for every 1 in 5 pages views to save email storage and server capacity?

    ( Reply )
  56. PG

    JohnGalt July 11th

    Nice tutorial.

    ( Reply )
  57. Thanks, great article.

    ( Reply )
  58. PG

    Ricardo Miller September 9th

    very nice script. But i am having some problems with it. i downloaded the source code and extract it to folder on my computer, i modified the error_mailer.php adding an email address where it said “email address to send to” i left everything else untouch for now.

    should i upload all the files in the folder i create to my server or should i upload all the files out of a folder in my root directory.
    should i put the 404.php and 403.php in a separate folder “name error” i got this from my error log

    [Wed Sep 09 16:13:36 2009] [error] [client IP Address "i remove this"] File does not exist: /home/thecomp2/public_html/404.shtml, referer: http://www.thecomputershop.me.uk/

    can you please instruct me in which way i should upload these files.
    i got the 500 internal server error so i when back and deleted the text from the .htaccess file (errorDocment 404 /error/404.php and 403.php) and then try my url again and my website came up perfectly. So i put the text back in the .htaccess file and i got the 500 internal server error could there a problem with the location of the 404.php/403.php files. please help me i spent over 6 hours trying to figure it out and i still haven’t got a clue

    ( Reply )
  59. PG

    sadakul islam September 30th

    fine information

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    September 30th