PHP Visitor Statistics

2010-02-16

This article describes how the gathering of visitor statistics is done on the previous version of hanswestman.se. It is a piece of PHP code that runs in the top of every page that will register a new, unique visitor to the website.

The script will only register new visitors once a day. This is to verify that it is not registered as a visitor moves from page to page. For every unique visitor, it saves IP address, browser, date and hour to a database. For this script, I have created a simple database table that contains just those properties. To avoid too much unnecessary calculation and database queries, I chose to set a $_SESSION variable for each active visitor during their session. The script first checks if the variable is active. Is it so the user has just been on a different page on the website, it does not need to be treated. If the visitor does not have a variable set, it means that there is a new visitor and it needs to be treated further. A $_SESSION variable is only active for a limited time before being removed, so I have chosen that the script will check the database if the user is new, before it is registered.

<?php
if(!isset($_SESSION['visitor_id']))
{
  $ip = $_SERVER['REMOTE_ADDR'];
  $browser = $_SERVER['HTTP_USER_AGEN'];
  if(preg_match('/chrome/i', $browser))
  {
    $browser = "Chrome";
  }
  elseif(preg_match('/safari/i', $browser))
  {
    $browser = "Safari";
  }
  elseif(preg_match('/opera/i', $browser))
  {
    $browser = "Opera";
  }
  elseif(preg_match('/msie/i', $browser))
  {
    $browser = "MSIE";
  }
  elseif(preg_match('/firefox/i', $browser))
  {
    $browser = "Firefox";
  }
  else
  {
    $browser = "Other";
  }

  $date = date("Y-m-d");
  $hour = date("H");

  if(!mysql_num_rows(mysql_query("SELECT * FROM stats WHERE IP = '$ip' AND day = '$date'")))
  {
    mysql_query("INSERT INTO stats (ip, browser, day, hour) VALUES('$ip', '$browser', '$date', '$hour')");
  }
  $_SESSION['visitor_id'] = session_id();
}
?>

The following SQL code can be run to create the database table used by the script:

CREATE TABLE stats (
  ID INT(11) NOT NULL AUTO_INCREMENT,
  IP VARCHAR(15),
  browser VARCHAR(100),
  day DATE,
  hour INT(2),
  PRIMARY KEY (ID)
);