Related Entries

Scalability myth
JpGraph - GD on steroids
PHP & Oracle performance
Fixes and improvements to IEEditor
Two useful articles on PHP

« Webtrends Sucks!
» Teaching Java

Quick script to log site hits

Simple PHP script that you can include in any SSI file or PHP file to create your own CLF server logs.

It is a long while since I programmed in PHP. However, the horrible experience with Webtrends Live gave me with little choice other than to write my own logging code. Quick look at the Apache common log format made sure this was easy enough task. Here’s a simple PHP include file that will do the trick. This works for me because I use SSI to setup my templates and it was a trivial matter to include this in another SSI include.

It is not perfect. No 404 error captures, no logs for images, CSS etc. It serves my needs though. Unlike Webtrends Live, it doesn’t take a millenium to get the reports. And I can finally kick out the non-XHTML code for Webtrends Live.

At the moment, I’m using AWStats for log file analysis. I need to incorporate this logging into rest of my site, but I’m deferring that till the whole site redesign.

<?php
/***
Simple php include file that will create an
Apache CLF logfile.
vsbabu - 08/21/2002
***/
/* --- configuration --- starts ---- */
$logfile "absolute_path_to_your_log_file";
//timezone your server is in
$timezone "-0600";
// Make it false if you don’t want filesize to be
// computed. Make it a bit faster.
$lookup_size true;
// root of my site and default document
$document_root "/home/vsbabu/www";
$default_document "index.html";
/* --- configuration --- ends ---- */
//client ip
$h $REMOTE_ADDR;
// - Indicates not found. This will never happen :-)
$l "-";
// Authenticated user. I don’t have password protected site.
$u "-";
// hit time
$t gmdate("d/M/Y:H:i:s");
$t "[$t $timezone]";

// url requested
/*
  $r = '"'. $REQUEST_METHOD . " " . $REQUEST_URI . " " . $SERVER_PROTOCOL . '"';
  SERVER_PROTOCOL gives INCLUDED. I know this is HTTP1.0, so hard
  coding it.
*/
$r "\"$REQUEST_METHOD $REQUEST_URI HTTP/1.0\"";
// status. again hard coded
$s "200";
if(
$lookup_size == true && $document_root){
  
//this is not entirely foolproof since for
  //default documents, the directory size will be returned
  
$filename ereg_replace("\?.*"""$REQUEST_URI);
  
$filename "$document_root$filename";
  if(
is_dir($filename))
    
$filename "$filename/$default_document";
  if(!
$b filesize($filename))
    
$b 0;
} else {
  
$b 0//this would be too much to calculate
}
$referrer "\"$HTTP_REFERER\"";
$headers getallheaders();
$agent '"' $headers['User-Agent'] . '"';
$fp fopen($logfile"a");
$log "$h $l $u $t $r $s $b $referrer $agent\n";
fwrite($fp$log);
fclose($fp);
?>
//-->