Update Google Analytics by PHP
Google Analytics is usually updated by embedding Javascript code into your web pages. If you've written a web application and want to add extra information into your analytics tracking then using PHP to update Google Analytics may be a better option (using Google's Analytics Measurement Protocol). To do this you'll need a web server with PHP and Curl installed and your Google Analytics tracking ID.
Check to see if Curl is installed
To check to see if the Curl module is installed as part of your PHP installation, cut and paste the following lines into a PHP document, save it and run it:
<?php
function _is_curl_installed() {
if (in_array ('curl', get_loaded_extensions())) {
return true;
}
else {
return false;
}
}
if (_is_curl_installed()) {
echo "cURL is <span style=\"color:blue\">installed</span> on this server";
} else {
echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";
}
?>
If you have Curl installed then you're ready to move on.
Required parameters
I'm going to talk through all the different elements of the script below and at the bottom of this article you'll find the finished script ready for use.
In the first part of the script we need to create the required parameters. These are as follows:
- Client ID (cid - generated by the gen_uuid function below) - anonymous unique id for this browser instance
- Analytics ID (tid) - your Universal Analytics ID (UA-*-)
- Protocol version (v) - the version number of Google's Analytics Measurement Protocol that we're using
- Type of hit (t) - must be one of 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'. I've used event for mine
Here's the first part of the code:
<?php
function gen_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
$data = array(
'v' => 1,
'tid' => 'UA-99999999-9',
'cid' => gen_uuid(),
't' => 'event'
);
?>
Additional parameters
A list of all the parameters that can be passed can be found on the Measurement Protocol Parameter Reference page.
Here's the code to assign some of the additional parameters, along with the url that you're going to pass the parameters:
<?php
$data['ec'] = "category";
$data['ea'] = "product";
$data['el'] = "element";
$data['ev'] = "34";
$data['uip']= $_SERVER['REMOTE_ADDR'];
$data['ua']= $_SERVER['HTTP_USER_AGENT'];
$url = 'https://www.google-analytics.com/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
?>
Note. You can change the $url variable to: `https://www.google-analytics.com/debug/collect` to test out your script which will give you a success message in the browser if its working fine.
Update the analytics data
The last part of the script takes all of the variables and updates the analytics data for you.
<?php
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>
Note . Setting the `CURLOPT_RETURNTRANSFER` flag is optional. I didn't want to get a response from the Google servers so I set it to `true`. If you want a response (a gif image) then omit this line.
Remember to use the real time view when you're viewing data in your Google Analytics account. If you leave it at the default setting then you'll only be looking at yesterday's data.
So that's that. All that remains is for me to provide you with the full code as I alluded to earlier Happy analysing!
<?php
function gen_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
$data = array(
'v' => 1,
'tid' => 'UA-99999999-9',
'cid' => gen_uuid(),
't' => 'event'
);
$data['ec'] = "category";
$data['ea'] = "product";
$data['el'] = "element";
$data['ev'] = "34";
$data['uip']= $_SERVER['REMOTE_ADDR'];
$data['ua']= $_SERVER['HTTP_USER_AGENT'];
$url = 'https://www.google-analytics.com/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>
This article was written by Gaz Hall, a UK based SEO Consultant on 20th September 2015.
Gaz has 20 years experience working on SEO projects large and small, locally and globally across a range of sectors.
If you need any SEO advice or would like him to look at your next project then get in touch to arrange a free consultation.