How to create and implement a pixel tracking code

Andrei Stalbe picture Andrei Stalbe · Feb 1, 2013 · Viewed 52.3k times · Source

OK, here's a goal I've been looking for a while.

As it's known, most advertising and analytics companies use a so called "pixel" code in order to track websites views, transactions, conversion etc.

I do have a general idea on how it works, the problem is how to implement it. The tracking codes consist from few parts.

  1. The tracking code itself. This is the code that the users inserts on his webpage in the <head> section. The main goal of this code is to set some customer specific variables and to call the *.js file.

  2. *.js file. This file holds all the magic of CRUD (create/read/update/delete) cookies, track user's events and interaction with the webpage.

  3. The pixel code. This is an <img> tag with the src atribute pointing to an image *.gif (for example) file that takes all the parameters collected on the page, and stores them in the database.

Example:

WordPress pixel code: <img id="wpstats" src="http://stats.wordpress.com/g.gif?host=www.hostname.com&amp;list_of_cookies_value_pairs;" alt="">

Google Analitycs: http://www.google-analytics.com/__utm.gif?utmwv=4&utmn=769876874&etc

Now, it's obvious that the *.gif request has to reach a server side scripting language in order to read the parameters data and store them in a db.

Does anyone have an idea how to implement this in Zend?

UPDATE Another thing I'm interested in is: How to avoid the user's browser to load the cached *.gif ? Will a random parameter value do the trick? Example: src="pixel.gif?nocache=random_number" where the nocache parameter value will be different on every request.

Answer

nickhar picture nickhar · May 6, 2013

As Zend is built using PHP, it might be worth reading the following question and answer: Developing a tracking pixel.

In addition to this answer and as you're looking for a way of avoiding caching the tracking image, the easiest way of doing this is to append a unique/random string to it, which is generated at runtime.

For example, server-side and with the creation of each image, you might add a random URL id:

<?php

  // Generate random id of min/max length
  $rand_id = rand(8, 8);

  // Echo the image and append a random string
  echo "<img src='pixel.php?a=".$vara."&b=".$varb."&rand=".$rand_id."'>";

?>