Google Analytics Measurement Protocol PHP script

search for: in: entire forum this post
you are here: root => Tech Tutorials => Google Analytics Measurement Protocol PHP script
member since:
folders:
3
posts:
7
replies:
0

Google Analytics Measurement Protocol PHP script

I wanted to add a counter to an image generated with PHP (for wIMG.ca) so I have created a PHP server-side counter code that uses the Google Analytic's Measurement Protocol. You can use it to add a counter to PHP generated images, XML (for ajax), video files, etc.. Enjoy!

code:
<?php
//This is a PHP script that sends hits to Google Analytics using the "Measurement Protocol"


//usage:
//
//To use this script, create a file called send_analytics.php and copy this entire code in it, then in your PHP script where you want to track the traffic, put the "usage code":
//
//PHP session must already be started!!
//============================start of usage code
//if(!function_exists("gen_uuid_forGA")) {function gen_uuid_forGA() {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 ));}}
//if(!isset($_SESSION['clientID_for_GA'])) {$_SESSION['clientID_for_GA']=gen_uuid_forGA();}
//exec('php send_analytics.php "UA-XXXXXXXX-X" "'.$_SESSION['clientID_for_GA'].'" "'.$_SERVER['HTTP_HOST'].'" "'.urlencode($_SERVER['REQUEST_URI']).'" "'.$_SERVER['REMOTE_ADDR'].'" "'.urlencode($_SERVER['HTTP_USER_AGENT']).'" "'.urlencode($_SERVER['HTTP_REFERER']).'" > /dev/null &');
//============================end of usage code


//============================start of send_analytics.php code
function post_with_curl_and_return_return($url,$data){
	$ohyeah = curl_init();
	
    curl_setopt($ohyeah, CURLOPT_URL, $url);
	curl_setopt($ohyeah, CURLOPT_TIMEOUT, 5);
	curl_setopt($ohyeah, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ohyeah, CURLOPT_MAXREDIRS, 10);
	
	curl_setopt($ohyeah,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
	curl_setopt($ohyeah,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
	curl_setopt($ohyeah,CURLOPT_USERAGENT, 'Example/1.0 (http://example.com/)');
	
	curl_setopt($ohyeah, CURLOPT_POST, TRUE);
    curl_setopt($ohyeah, CURLOPT_POSTFIELDS, $data);
	
	curl_setopt($ohyeah, CURLOPT_RETURNTRANSFER, 1);
	
    $data = curl_exec($ohyeah);
    curl_close($ohyeah);
    return $data;
}




//values to be sent with the hit, reference: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
$data_array['payload_data']='';
$data_array['v']=1; //The Protocol version. The current value is '1'. This will only change when there are changes made that are not backwards compatible.
$data_array['tid']=$argv[1]; //The tracking ID / web property ID. The format is UA-XXXX-Y. All collected data is associated by this ID
$data_array['cid']=$argv[2]; //The client ID. This anonymously identifies a particular user, device, or browser instance. For the web, this is generally stored as a first-party cookie with a two-year expiration. For mobile apps, this is randomly generated for each particular instance of an application install. The value of this field should be a random UUID (version 4) as described in http://www.ietf.org/rfc/rfc4122.txt
$data_array['t']='pageview'; //The type of hit. Must be one of 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'.
$data_array['dh']=$argv[3]; //The document host. Specifies the hostname from which content was hosted.
$data_array['dp']=$argv[4]; //The document path. The path portion of the page URL. Should begin with '/'.
$data_array['uip']=$argv[5]; //The IP address of the user. This should be a valid IP address. It will always be anonymized just as though &aip (anonymize IP) had been used.
$data_array['ua']=$argv[6]; //The User Agent of the browser. Note that Google has libraries to identify real user agents. Hand crafting your own agent could break at any time.
$data_array['dr']=$argv[7]; //The document referrer. Specifies which referral source brought traffic to a website. This value is also used to compute the traffic source. The format of this value is a URL.


$data=http_build_query($data_array);
$data = utf8_encode($data); // The payload must be UTF-8 encoded.
echo 'data:'.$data.'
';

$what_it_says=post_with_curl_and_return_return('http://www.google-analytics.com/collect',$data);
echo htmlspecialchars($what_it_says).'
';

//============================end of send_analytics.php code
?>

post #48
permalink
a guest
I am extremely pleased that you have shared this script here. My mates who do essay writing https://www.ukessaysreviews.com/uk-superiorpapers-com-revie​w/ were asking for this script for ages and now, I can finally give them this.
post #125
permalink
member since:
folders:
0
posts:
0
replies:
1
This is a great article, that I really enjoyed reading. Thanks for sharing.
soundcloud to mp3 converter, KissManga grand blue
post #139
permalink

moderators of this post

envis (level: ∞)
powered by Nodesforum