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.
About Error Pages

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.

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

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.

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?
- I don't want to log into my server every day and dig through all that extra information.
- 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.
- 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.
- 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:
- Internet Explorer requires error pages that are at least 512 byes in size (if you use the example files you'll be fine)
- 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
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.











User Comments
( ADD YOURS )Colin McFadden April 17th
Great tutorial, man! Very helpful =)
( )Saro April 17th
Thanks
( )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/
Ali April 17th
thanks … very awesome
( )BluE-=-FaLcOn April 17th
THANKS DEAT
( )Philo April 17th
Already knew this!
( )Great article though!!
lawrence77 April 17th
Then you miss to write a tutorial here!
( )Philo April 17th
True
But don’t worry, trying to get 2 exciting tutorials published this month!
lawrence77 April 18th
what are the tutorials?
I didn’t notice that before sending!
yup, You already write 3 tutorials!
Me too try to write tutorials……
Mukarram April 17th
Nice article….keep it up more !!!
( )rob j April 17th
I like it!
( )iPad April 17th
I didn’t know we can achieve this! thanks!
( )wayno007 April 17th
Thanks, great article.
( )yeahman May 4th
yea man
( )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.
( )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.
( )Random Gemini April 17th
Great article Jarel! You’re improving my blog by leaps and bounds every time you post!
( )crysfel April 17th
thanks you, this is really useful.
thanks again
( )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.
( )Neil April 17th
.Net has much better 404/500 handling using a global.asax
( )Shane April 19th
The CustomErrors section of web.config vs. .htaccess…
arguable…
( )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*
( )Taylor Satula April 17th
Huh, Thanks Very Helpfull
( )Good tut. No problems
Craigsnedeker April 17th
Already have a custom one
But good tut none the less.
http://snedekerdesignz.com/ss
( )Joe April 17th
Great! More user-friendly.
( )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.
( )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.
( )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.
( )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.
( )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.
( )Mason Sklut April 17th
Nice post Jarel!
( )Rachel April 17th
FYI… I attempted to add you to my Shrook RSS feed. I get an ‘XML not readable’ error message.
( )Rachel April 17th
Skip my last comment (and please don’t post it.) Worked when I used the RSS button in the url window.
( )Rahul Chowdhury April 17th
Thanks man, great tutorial, I needed this for the phpMail(), thanks for it.
( )Ignas April 18th
nice one
( )Lamin Barrow April 18th
Very useful. Thanks so much.
( )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
Jarel April 19th
Thanks for the comments everyone! Much appreciated
( )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!
( )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.
( )David Singer April 19th
Cool article. I like Swift Mailer better than auto mailer though… Same idea though.
( )Ronald April 20th
Is it possible to use this on a Microsoft IIS server, with php?
( )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.
( )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.
( )Martyn Web April 20th
Very Helpful tutorial!
I look forward to testing it out.
Thanks
( )rafaelrrp April 20th
Thanks!!!!!
( )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.
( )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!
( )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..
( )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!
( )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
Ryan April 23rd
Great read… This will be going up on my website! Thanks
( )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.
( )www.fkra4all.co.cc April 29th
hi and thanks for every thing
( )Aria Rajasa May 12th
Awesome! I miss this one.. will implement it right away
( )mary May 12th
Awesome!! This is going to be a great help for me!
thanks
( )koko May 15th
Can I sent to two email?
# The email address to send to
$to_email = ‘email1′;
how can I implement it?
( )БAKИHEЦ May 23rd
Эээ, а объясните, пожалуйста, а то я что то не совсем въехал в тему, это как?
( )spoon5 May 27th
Nice work, keep it up!!!
( )Homeeg June 4th
Nice work Keep it Up
( )John June 13th
Thanks for the tutorial, very handy.
( )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.
( )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?
( )JohnGalt July 11th
Nice tutorial.
( )P.C. Helpline Australia July 24th
Thanks, great article.
( )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
sadakul islam September 30th
fine information
( )