Devin Ellis

Google Analytics Request PHP Class


I recently needed a way to make a Google Analytics tracking request in the background, using PHP with no javascript, while serving up an image. After 2 seconds of googling, I came across an old blog post by Peter van der Graff. Like 2007 old.

Basically, the Google Analytics javascript builds a url to a GIF file that includes all of the tracking data as GET variables. So Peter’s idea was to simply recreate the URL building using PHP, and make the request in the background using fopen(). This would fit my needs, as I could build and make the GA request in the background, and then fetch and serve the JPG data to the browser. So basically I converted his original code into a GoogleAnalyticsRequest() class, making it very easy to make these requests:

 $ga = new GoogleAnalyticsRequest(); // pass TRUE = debug
 $ga->domain   = '';
 $ga->account  = 'UA-12345678-1';
 // $ga->custom defaults to user's IP.

The GoogleAnalyticsRequest.php class can be found here.

I haven’t done extensive testing on this, and I think its using the old Urchin GA request type, but I think it will do for my purposes. Leave a comment if you have any suggestions on how to improve this.