404/403 Website Error Pages With PHP Auto-Mailer


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

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:


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.


# The email address to send to
	$to_email = '';

# 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 = '';

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
    $mail = new PHPMailer();

    $mail->From = $from_email;
    $mail->FromName = $from_name;
    $mail->Subject = $email_subject;
    $mail->Body =
    "There was a ".$error_code." error on the ".$server_name." domain".
    "\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;



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



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


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


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
  • Code
    Web Development
    How to Use New Relic With PHP & WordPressRelic retina preview
    Today we will look at how to monitor a PHP application using New Relic. More specifically we will set up a basic WordPress installation and get some performance data about it, in the New Relic dashboards.Read More…
  • Code
    Web Development
    Securely Handling User's Login CredentialsSecure wide retina preview
    Consider the following tips on how to properly secure your user's login credentials.Read More…
  • Code
    The Beginner’s Guide to WordPress SEO by Yoast: Final TweakingThe beginners guide to wordpress seo by yoast
    In my previous article, I discussed the social settings of Yoast's WordPress SEO plugin. In this tutorial, you will learn the final steps to configuring the WordPress SEO plugin with the ultimate goal of making it as rock-solid as possible for your blog.Read More…
  • Code
    Sending Emails With Laravel 4 & GmailLaravel 4 auth retina preview
    Sending emails is crucial for any web application. Usually, an email is sent to notify the user of some kind of activity that has taken place on the site, for example, such as when updates have been made or when new friends have been found. In this short tutorial, I'll show you how to send emails with Gmail quickly from within a Laravel sample application by extending the functionality that we built in my last tutorial, Authentication With Laravel 4.Read More…
  • Code
    Creative Coding
    A Look at the WordPress HTTP API: wp_remote_get - the ResponseDiagram http api
    In this series, we've been taking a look at the wp_remote_get WordPress HTTP API function in order to understand how it works, how we can use it, and the optional arguments that it accepts. From here, we're able to write detailed requests; however, that's only half of it - there's also the response. In the second article, we took a look at what a basic response would look like, how to evaluate it, and how to display it on the screen, but we didn't actually talk about the response in detail. If you're looking to write more advanced requests and write more defensive code, then it's important to understand the data that's sent as a response. In this final article, we're going to do exactly that.Read More…
  • Web Design
    All You Need to Know About XML SitemapsPreview
    When we talk about sitemaps, most people think about a web page with links on it. There is however a more useful type of sitemap: the XML Sitemap. What are the benefits of having one? Are there other types? How is an XML Sitemap created? Read on to find out..Read More…