views:

31

answers:

1

Does Google Analytics store the utm_source, utm_medium paramaters in a cookie or something similar that I can access on my own site using PHP? - OR - does anyone have an example of code I could use to identify a traffic source ie. PPC, Natural etc.

+1  A: 

Yes, Google stores this information in a cookie; specifically, the __utmz cookie.

You can write a piece of JavaScript to read the cookies that GA stores in the browser. This information is stored in the __utmz cookie. For example, if a link contained all 5 possible utm variables, the cookie would look something like this (I've substituted the capitalized names for the values, so SOURCE is the value for utm_source:

     43838368.1283957505.1.3.utmcsr=SOURCE|utmccn=CAMPAIGN|utmcmd=MEDIUM|utmctr=TERM|utmcct=CONTENT

This is what a __utmz cookie looks like for an organic google search:

140029553.1283957328.2.136.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=SEARCH-TERMS-HERE

This is what a __utmz cookie looks like for a direct visit:

   17861479.1283957910.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

This is what a __utmz cookie looks like for paid google search with autotagging:

   175516223.1283957996.1.1.utmgclid=CLrr7fyL-KMCFZpN5QoduVOTLA|utmccn=(not%20set)|utmcmd=(not%20set)|utmctr=SEARCH+TERM

PHP is not ideal, since you could never read the cookie on single-page-visits, but here is what the code could look like in PHP.

if(isset($_COOKIE['__utmz']))
{
$cookie= $_COOKIE['__utmz'];
$params =  strstr($cookie, 'utm');
$cookiearray = explode("|", $params);
$final = array();
for($i=0; $i<count($cookiearray); $i++)
{
    $temp = explode("=",$cookiearray[$i]);
    $final[$temp[0]] = temp[1];
}
}

This would give you an array ($final) with key-value matches for each traffic source parameter.

You'd probably be better off parsing this in JavaScript and posting it to your server using AJAX, rather than reading it on the server-side, since you could only do that on the second page view, and would thus lose the ability to track single-page-view users. This can be an annoying task with manual JavaScript, because both cookies and AJAX can be inconsistent across browsers, so I would recommend a framework like jQuery.


Here's the approach I would take using jQuery. I'd add the jQuery cookie plugin, and post it within a $(document).ready() clause like this (assuming that the PHP above is stored in handler.php)

$.post('handler.php', '__utmz' : $.cookie("__utmz") );

Then, switch the two references of $_COOKIE to $_POST, and do whatever you want with the array it produces.

yc
Do you have a Javascript example using Jquery on how to do this?
See my edits above.
yc