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
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);