Title: Building a micro-stats logger in PHP
Slug: building-a-micro-stats-logger-in-php
Date: 2011-11-03 23:15:35
Author: Kartones
Lang: en
Tags: Development, PHP, Javascript, Wordpress
Description: A tutorial on building a micro-stats logger in PHP as an alternative to Google Analytics, detailing the process of creating a system for testing stats on a Wordpress blog.

 <p>Searching for a solution to avoid the Google Analytics ga.js (I want to have as few external JS as possible, plus its stats logging are not 100% accurate) I decided to build my own system to do some testing (I will follow up with the final solution).</p> <p>In this case the code will be PHP and JQuery for the Javascript part, because I wanted to test the stats with a Wordpress blog.</p> <p>Google Analytics does a GET request to do the tracking because they ask for a tracking pixel (1x1 gif image), but as I'm going to launch a direct query, I will do a POST which is more HTTP correct (changes state).</p> <p>Also, as browsers can run in paralel requests to different subdomains, I setup <em>stats.xxxxx.com</em> to send the queries there instead of the main domain.</p> <p> </p> <p>The data to send is quite simple, the page I was in and the post ID if present. I store it in <font face="Courier New">$_SESSION['stats']</font> so that all Wordpress template files can set their stats, and then just do this in the footer.php template:</p> <p><font face="Courier New">&lt;? if (isset($_SESSION['stats'])) { ?&gt;<br>    $.post("http://stats.xxx.com",{ s: "&lt;?= $_SESSION['stats'] ?&gt;" });<br>&lt;? } ?&gt;</font></p> <p> </p> <p>Tip: Place this code inside <font face="Courier New">jQuery(document).ready</font>  so that it waits for eveything else to be ready. Remember, logging stats is not prioritary, first show everything to the user then send the logging request.</p> <p> </p> <p>On the serverside, I just checked for <font face="Courier New">$_POST['s']</font> and logged it among other stuff:</p> <ul> <li><font face="Courier New">$_SERVER['REMOTE_ADDR']</font> (anonymizing the fourth octect by setting it to 0 as Google Analytics does)  <li><font face="Courier New">$_SERVER['HTTP_USER_AGENT']</font>  <li><font face="Courier New">$_SERVER['HTTP_ACCEPT_LANGUAGE']</font>  <li>...</li></ul> <p>Tip 2: Also add this header to the tracking PHP file so that there are no modern browser complains about cross-origins:</p> <p><font face="Courier New">header('Access-Control-Allow-Origin: http://www.xxxxx.com');</font></p> <p> </p> <p>And that's all. How do you store it, what else to store, how to retrieve and display stats and anything else is left to you. I was simply logging to files splitted by <em>year-month-day</em>.</p> <p> </p> <p>For the record, the experiment worked really well and the logging/tracking was really fast. I just discarded it to take advantage of the Google Analytics data displaying website, but even that could be added with some effort in here.</p>
