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:
1

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
a guest
I wonder if someone could get me the is Superiorpapers legit here because i really need that and i cant find that kind of help anywhear !!
post #170
permalink
a guest
I honestly thought that there would be some drone with camera for sale here so why is that not here at all i honestly thought it would be here !
post #173
permalink
a guest
Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as. long island pr agencies

post #202
permalink
a guest
This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!.. prweb

post #218
permalink
a guest
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. media coverage

post #232
permalink
a guest
The Ideal Dream Laser Clinic is a cosmetic-medical center offering only certified, result-oriented hair removal, Skin rejuvenating, body countering and weight loss services for both men and women. Our team includes certified technicians, Registered Dietitian and specialized skin and laser consultants. We offer the highest level of safety and service in an environment where the main priority is your safety, health and privacy. Our clinic located in heart of north York , Yonge and Steeles area close to public transit. 5 min walk to center of Yonge and Steeles, 88 Steeles Ave. East Toronto. laser hair removal north york

post #252
permalink
a guest
Thanks for this post!! it was great reading this! keep posting!! i would like to receive more info on this!! Stay connected! best link building

post #280
permalink
a guest
Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing... webdesign

post #282
permalink
a guest
nice post, keep up with this interesting work. It really is good to know that this topic is being covered also on this web site so cheers for taking time to discuss this! Funeral And Cremation Services

post #283
permalink
a guest
Many thanks for the exciting blog posting! Simply put your blog post to my favorite blog list and will look forward for additional updates. Simply wanted to write down a word in order to say thanks to you for those wonderful tips. notebook asus i5 8gb 1tb
post #284
permalink
a guest
Hey, Loved it. Thanks For sharing this post with us.
Fix Your Technical Problem With us. We are a team of the tech geeks. problem with Router, antiviruses, Windows, printer etc. Visit
Install belkin router
post #326
permalink
a guest
Thanks for sharing this marvelous post. I m very pleased to read this article. Belkin.setup
post #332
permalink
a guest
Thanks for sharing this marvelous post. I m very pleased to read this article. Belkin.setup
post #338
permalink
a guest
we provide help and support for Setup, Activation and Installation of all type of PC, Laptop software please visit our pages related to
mcafee.com/activate or directly visit
mcafee activate .
you can find more topics there.We love to help you.
post #356
permalink
a guest
nice.. valuable information..here is users can get instant tech support for ..
linksys login
post #489
permalink
a guest
post #693
permalink
a guest
Do you need help for belkin router setup ? check out this article and follow the instructions to fix the problem.
post #966
permalink

moderators of this post

envis (level: ∞)
powered by Nodesforum