Server-side Google Analytics

In late 2009 Google announced a new Analytics SDK used for tracking events inside iPhone and Android applications. The same release also featured a new method for more accurate tracking running Analytics server-side instead of using JavaScript. This especially comes handy when developing mobile websites.

Many older phones suffer from the lack of JavaScript support. Which in some cases makes it more complicated to track the user. But running the tracking service server-side will solve this problem easily.

As mentioned earlier Google does offer a server-side solution for Analytics. Sadly enough the documentation is almost non-existing and the only thing provided is some crappy PHP example code to get you started.

Therefor I wrote a simple class in PHP used for interacting with the server-side solution for Analytics. The logic and flow is provided by the existing example code. Below you’ll find a brief description of the “flow“.

A user comes to your site and the url function will generate an uri with all mandatory parameters included. This uri is will be included in the src attribute inside an img element. The browser will then request the uri believing that it’s an image. The uri will actually be pointing to a executable script. In this script the track function is called. A unique visitor id will be generated and stored inside a cookie. An HTTP-request will be sent to Analytics including all kind of parameters in order to track the user. When the request is done a 1×1 GIF image will be severed in order to satisfy the browser.

The method described above is a quite common way of solving lack of JavaScript related problems.

In order to start using this tracking method you’ll need to create a new Analytics profile for your website.

  • Create a new profile.
  • Select “tracking for a new domain” or new subdomain if applicable.
  • Click on the “Advanced” tab and choose the mobile option.
  • Copy your new Analytics ID from the textarea (MO-XXXXXX-XX).

The code is available on GitHub so feel free to fork away! There’s also a demo included in the repository. Should be just enough to get you started.

To all CodeIgniter fanboys out there. The class works perfectly as a library in CodeIgniter. You just need to make sure to include the uri generated from the url function inside your view. And then point it towards a function in your controller which executes the track function. See the demo inside the repository for further reference.

Happy accurate tracking!

Photo credit: Antonio Manfredonio.