STRUCTURALdeviations - Journal

PHP - Custom 404 Error Pages with Email Notification

Here’s a custom PHP function I find I'm using over and over again, so I thought I'd put it here for future prosperity. I use it at work to help monitor broken links across our range of sites — the beauty is, if it can, it’ll tell you where the broken link came from (either internally or from an external site).

function error404() {
$time = date("D M j Y, H:i:s"); // Tues Jan 25 2005, 16:25:36
$message = stripslashes(
"REQUESTED: http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].
"REFERRED FROM: ".$_SERVER['HTTP_REFERER'].
"USER AGENT: ".$_SERVER['HTTP_USER_AGENT'].
"VIA: ".$_SERVER['REMOTE_ADDR']." / ".gethostbyaddr($_SERVER['REMOTE_ADDR']).
"ON: ".$time);
$to = "webmaster@disegno.com.au";
$subject = "Error (404) from ".$_SERVER['SERVER_NAME'];

mail($to,$subject,$message);
}

To use, just create your custom 404 page as you would normally, then add the following somewhere on the page (I use the header) to call the function:

  <?php error404() ?>

Now you'll be notified whenever there are broken links on your site, and you'll be able to see where they're coming from.

 1