404 Logging

I decided to setup my 404 page to log the wrong addresses people are attempting to use on my site to a mysql database. A simple version of the script below, add it to your 404 page and input the right login and table details.

< ?php
mysql_connect("localhost", "user", "") or die("Cannot connect to DB!");
mysql_select_db("site") or die("Cannot select DB!");

$ip = getRealIpAddr();
$address = mysql_real_escape_string($_SERVER['REQUEST_URI']);

$insert = "INSERT INTO `404_log` (`address`, `ip`) VALUES ('$address' , '$ip')";
mysql_query($insert); 

function getRealIpAddr(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
    $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
?>

getRealIpAddr function from here

Some SQL to setup the table.

CREATE TABLE IF NOT EXISTS `404_log` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `address` varchar(500) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `ip` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.