I recently noticed in my sats that a bunch of the 404 errors that were logged were most likely hacking attempts. So, since I didn’t want to keep going back to logs to figure out who did what, I threw together a little code that can be inserted into any html file that is stored on a host that supports php. The code provides a warning for the person trying to access a file that does not exist, and it also sends an e-mail to me when such a thing happens.
Several of the functions and variables accessed in these calls are dependent on the configuration used by your host. But it does work for me, just try accessing a page that does not exist.
<?php
//Get which URL is being accessed
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];//Get IP of person trying to access site
$ip = $_SERVER['REMOTE_ADDR'];//Get more detailed information about the person trying to access the page (need to convert array into string and add linebreaks
$serverInfo = var_export($_SERVER, true);
$serverInfo = str_replace(',', "\n", $serverInfo);//Display warning msg
echo "<h1>NOTE: Your IP address is: $ip </h1>";
echo "<p>Your attempt to access $url has been logged and if you are trying to hack the site, appropriate measures will be taken against you!</p>";//Send the e-mail to yourself with all the details
$to = 'whomever@whererver.com';
$subject = '404 notification from mysite';
$message = $ip." tried to access ".$url."\n\n Info about request:\n".$serverInfo;
$headers = "From: webmaster@csaba.se\r\nReply-To: webmaster@csaba.se";
$mail_sent = @mail( $to, $subject, $message, $headers );
//un-comment the following line if you want confirmation of the e-mail sent being shown on the 404 page
//echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Enjoy!
Läs även andra bloggares åsikter om php, hacking, wordpress, 404