Herself’s Webtools

Webtools for Webmasters: Scripts, HowTos, Templates, Plugins, Widgets, Tips and Useful Information

Herself’s Webtools header image 1

Email yourself when someone gets a 404 error on your site

November 21st, 2007 · 3 Comments

It used to be all the web hosts gave you full access to log files and error files. Somewhere along the line that changed. Now they all want you to pay extra for log file access. But we have PHP so we can do our own logging.

When a user requests a page that is not on your site he is directed to your 404 page. Most web hosts let you totally customize this page.

On a regular website add the following code to your 404 page:

<?php
$url = $_SERVER[ 'REQUEST_URI' ];
$message = “URL: $url “;
wp_mail( youremail@yahoo.com, ‘404 error’, $message);
?>

Change youremail@yahoo.com to where ever you send email from your website. I don’t recommend sending this to your main email account. If some badly written spider gets tangled in your web you don’t want 500 emails in your main email that you use to communicate with friends and family.

If you are using Wordpress add the following code to the 404 Template page in your template:

<?php
$url = $_SERVER[ 'REQUEST_URI' ];
$message = “URL: $url “;

wp_mail(get_option(’admin_email’), sprintf(__(’[%s] 404 Error’), get_option(’blogname’)), $message);

?>

Now what happens if you get some spider or human that refuses to believe you do not have a copy of ‘nakedmoviestar.html’ and you no longer want 300 emails every day about this? You could do a 301 redirect to your local church or you can change your code like so:

<?php
$url = $_SERVER[ 'REQUEST_URI' ];
$message = “URL: $url “;
if ( !ereg(”nakedmoviestar.html”, $message )){
wp_mail(get_option(’admin_email’), sprintf(__(’[%s] 404 Error’), get_option(’blogname’)), $message);
}
?>

The if ( !ereg(”nakedmoviestar.html”, $message )){ } can be used on regular as well as WP set ups. Ah, but what if you have more than one idiot out there and you want to block emails about ‘nakedmoviestar.html’ and ‘windowshack.html’? Just add more if statements:

if (( !ereg(”nakedmoviestar.html”, $message )) || ( !ereg(”windowshack.html”, $message))){
wp_mail(get_option(’admin_email’), sprintf(__(’[%s] 404 Error’), get_option(’blogname’)), $message);
}

You can add as many || (!ereg(”filename”)) as you need.

Now when ever someone requests a page not on your server you’ll get an email so you can fix it asap.

Tags: how to · security

3 responses so far ↓

You must log in to post a comment.