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).
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.
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).
Also, as browsers can run in paralel requests to different subdomains, I setup stats.xxxxx.com to send the queries there instead of the main domain.
The data to send is quite simple, the page I was in and the post ID if present. I store it in $_SESSION['stats'] so that all Wordpress template files can set their stats, and then just do this in the footer.php template:
<? if (isset($_SESSION['stats'])) { ?>
$.post("http://stats.xxx.com",{ s: "<?= $_SESSION['stats'] ?>" });
<? } ?>
Tip: Place this code inside jQuery(document).ready 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.
On the serverside, I just checked for $_POST['s'] and logged it among other stuff:
- $_SERVER['REMOTE_ADDR'] (anonymizing the fourth octect by setting it to 0 as Google Analytics does)
- $_SERVER['HTTP_USER_AGENT']
- $_SERVER['HTTP_ACCEPT_LANGUAGE']
- ...
Tip 2: Also add this header to the tracking PHP file so that there are no modern browser complains about cross-origins:
header('Access-Control-Allow-Origin: http://www.xxxxx.com');
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 year-month-day.
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.
Tags: Development