2

Main Idea

I am working on a project and I need to use Google Analytics server side. I do not need to retrieve information, but I need to send information. I could eventually send js script client side, but in this scenario it is not an option.

Most of the following links are really old. 2012~

Retrieving - Not what I need

I have read multiple StackOverflow posts, but they only mention ways to retrieve information.

PHP API for Google Analytics(SO)

Sending - What I need

There is this one post talking about sending information but the GitHub has been deprecated for that library.

Google Analytics PHP API Redirect URI (SO)

Google api php client(GOOGLE)

Question

How do I send information to my Google Analytics account in PHP? Thanks

Community
  • 1
  • 1
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131

2 Answers2

12

Be very careful... Google is able to retrive lot of user informations regarding user-agent, location, ip, campaign, language and so on, using cookies and browser features. All commands are usually sent using a client-side js script because of that. If you want to work in server-side you have to handle all the necessary information you need to collect in your statistics before to send the HIT. For example, if you don't handle UUID properly, google will consider every HIT as "new visitor". If you want to know the geo location of users and your server is in Ireland, every hit made by user will be considered made by an Irish guy. Every ip will be the same of your server, and so on. I made a custom library using php that consider all these problems. Basically you can use curl:

function SendGoogleEvent($userid,$category,$action, $label='',$eventvalue=0,$campaign_name='direct',$campaign_source='organic',$campaign_medium='organic'){
$strCookie='';
foreach ($_COOKIE as $key => $value) {
    $strCookie.=$key.'='.$value.'; ';
}
$fields_string='';
$fields = array (
    'v' => 1,
    'tid' => "YOUR GA ID",
    'cid' => $userid,
    'uip' => $_SERVER['REMOTE_ADDR'],
    'dh' => "your site address",
    'ul' => 'it-it', // In this case i dont care the user language
    't' => 'event',
    'ec' => urlencode($category),
    'ea' => urlencode($action),
    'el' => urlencode($label),
    'ev' => $eventvalue
);  
if ($campaign_name!='direct') {
    $fields["cn"]=$campaign_name;
}
if ($campaign_source!='organic') {
    $fields["cs"]=$campaign_source;
}
if ($campaign_medium!='organic') {
    $fields["cm"]=$campaign_medium;
}
if (!(substr($_SERVER['HTTP_REFERER'], 0, strlen("your site url")) === "your site url")&&$campaign_name=='direct') {
    $fields["dr"]=$_SERVER['HTTP_REFERER'];
}
foreach($fields as $key=>$value) {
     $fields_string .= $key.'='.$value.'&'; 
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, utf8_encode($fields_string));       
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL,"https://ssl.google-analytics.com/collect");
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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_COOKIE, $strCookie );
curl_exec( $ch );
curl_close($ch);
Marcello Kad
  • 186
  • 1
  • 7
5

You send data via the Measurement Protocol. No special library or dev kit is required, you simply append parameters to the GA endpoint and send them via Curl/fopen/sockets/whatever to Google Analytics.

Each calls includes at least the ID of the account you want to send data to, a client id that allows to group interactions into sessions (so it should be unique per visitor, but it must not identify a user personally), an interaction type (pageview, event, timing etc., some interactions types require additional parameters) and the version of the protocol you are using (at the moment there is only one version).

So the most basic example to record a pageview would look like this:

www.google-analytics.com/collect/v=1&tid=UA-XXXXY&cid=555&t=pageview&dp=%2Fmypage
Eike Pierstorff
  • 31,996
  • 4
  • 43
  • 62