Simple analytics

How to count the number of unique visitors per day? Just create an empty file analytics.log and add this simple logging code at the end of index.php:

<?php 
$txt = date("Y-m-d") . "\t" . date("H:i:s") . "\t" . $_SERVER['REMOTE_ADDR'] . "\t" 
    . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER['HTTP_USER_AGENT'] . PHP_EOL; 
file_put_contents('./analytics.log', $txt, FILE_APPEND);
?>

Doing python analytics.py with this Python code will display the number of unique visitors for each day, in a human readable way:

import csv
S = dict()
with open('analytics.log', 'rb') as f:
  reader = csv.reader(f, delimiter='\t')
  for row in reader:
    if row[0] not in S:        # row[0] is the date in year-month-day format
      S[row[0]] = set()        # let's use a set in order to count each IP only once a day
    S[row[0]].add(row[2])      # row[2] is the IP 

for k in sorted(S):
  print k + ': ' + str(len(S[k]))

The result will look like this:

2015-04-19: 226
2015-04-20: 326    
2015-04-21: 303

If the number of visitors per day is enough for you (it is for me), you don't need to use Google Analytics. Let's keep it simple and stupid!