<?php
/* create a .htaccess file in your root and enter these most common error code definitions

ErrorDocument 400 /error.php?err=400
ErrorDocument 401 /error.php?err=401
ErrorDocument 403 /error.php?err=403
ErrorDocument 404 /error.php?err=404
ErrorDocument 500 /error.php?err=500

*/

// save this code below in file name "error.php"
if (isset($_GET['err'])) { 
    $errorNum = $_GET['err'];
} else {
    $errorNum = "undef. number";
}

$emailaddress = "your@mail.com";
/* 
you have to create this file and enter there all URL's with bad links and 
all IP addresses which are hot linking not existing files, example:
146.34.34.110
http://www.somedomain.com/filename.htm
*/
$filename = "http://".$_SERVER['HTTP_HOST']."/blocked_ref.txt";

// if the http referer is not empty  check the file for exsiting URL's 
if (!empty($_SERVER['HTTP_REFERER'])) {
    $bad_ref = file ($filename);
    $bad_counter = 0;
    foreach ($bad_ref as $val) {
        if (substr($_SERVER['HTTP_REFERER'], 0, 20) == substr($val, 0, 20)) {
            $bad_counter++;
        }
    }
    if ($bad_counter > 0) {
        header("Location: http://".$_SERVER['HTTP_HOST']);
        die();
    } else {
        $errortime = (date("d M Y h:m:s")); 
        $message = $errorNum." Error Report\r\n\r\nA ".$errorNum." error was encountered by ".$_SERVER['REMOTE_ADDR'];
        $message .= " on $errortime.\r\n\r\n";
        $message .= "The URI which generated the error is: \nhttp://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."\r\n\r\n";
        $message .= "The referring page was:\n".$_SERVER['HTTP_REFERER']."\r\n\r\n";
        $message .= "The used client was:\n".$_SERVER['HTTP_USER_AGENT']."\r\n\r\n";
        $headers = "From: ".$emailaddress."\nDate: ".$errortime." +0100\n";
        $subject = "Error: ".$errorNum." from ".$_SERVER['HTTP_REFERER'];
        mail($emailaddress, $subject, $message, $headers);
    }
} else { // at last check if there are already some bad IP Addresses
    $bad_ref = file ($filename);
    $very_bad_counter = 0;
    foreach ($bad_ref as $val) {
        if (substr($_SERVER['REMOTE_ADDR'], 0, 10) == substr($val, 0, 10)) {
            $very_bad_counter++;
        }
    }
    if ($very_bad_counter > 0) {
        header("Location: http://www.google.com"); // or some other nice URL
        die();
    }
}
// place here the html code you want to show the visitor, like
echo "<p>Some error...</p>";
?>