February 4th, 2012

I Can’t Access My Log Files!

As a web analyst it is important for me to track who comes to my site. For this reason I have installed the Google Analytics page tag, however Google’s privacy policy prevents it from displaying detailed data about site visitors. This doesn’t help when trying to segment visitors or do any in-depth analysis.

This website like many others in the web is hosted by a third party and they don’t supply me with any log files. So…I decided to create a PHP script that will record web log data into my own log files. There are some problems with this in that no requests for images, flash files, pdfs etc are recorded but it should record page views quite accurately.

If you are interested in recording log file data but don’t have access to your logs then you can use the script below.

To use effectively you will need to insert an include to this file in your web site header.php and also specify the $directory variable for where you want the logs to be stored.

Once you have log files you can then import them into a web log analyser for analysis.

Enjoy!

I have created a WordPress plugin based on this script which can be found here – Web Log Generator WordPress Plugin


//define confiuration variables
$directory = "/home/matt/logs/";
//todays date
$today = date("dmy");
//construct log entry
$datetime = date("d:m:y:H:i:s:O");
if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
else $ip = "UNKNOWN";
$request = $_SERVER['REQUEST_URI'];
$referrer = $_SERVER['HTTP_REFERER'];
$useragent = $_SERVER['HTTP_USER_AGENT'];
$method = $_SERVER['REQUEST_METHOD'];
$logline = $datetime . " " . $ip . " " . $request . " '" . $referrer . "' '" . $useragent . "' " . $method . "\n";
//open log file
$logfile = $directory . $today . ".log";
$fh = fopen($logfile, 'a') or die("Can't open file");
//write log entry
fwrite($fh, $logline);
fclose($fh);
?>

Comments are closed.