Reading:
Send Google Analytics Event with PHP

Send Google Analytics Event with PHP

Metamug
Send Google Analytics Event with PHP

This article assumes you are already familiar with Google Analytics (GA) and know how to send Events using the Google Analytics Javascript library. If you want to understand how to create GA events, this article can help you.

Sending Event using Javascript

Here's an example of how you would send a GA (Google Analytics) Event using the JS from the browser:

ga('send', {
    hitType: 'event',
    eventCategory: 'Console',
    eventAction: 'submit',
    eventLabel: 'Feedback Form Submission'
});

Using PHP instead of Javascript

The same Event given above can be sent using PHP on the server-side by making a POST request to the Google Analytics API along with the Event data. Here, I have used Curl to make the request:

// GA curl
$req = curl_init('https://www.google-analytics.com/collect');

curl_setopt_array($req, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POSTFIELDS =>
    'v=1&t=event&tid=UA-XXXXXXXX-X&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&ec=Console&ea=submit&el=Feedback%20Form%20Submission'
));
// Send the request
$response = curl_exec($req);

Analysing POST parameters

We can see that there are 7 post request parameters v=1&t=event&tid=UA-XXXXXXXX-X&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&ec=Console&ea=submit&el=Feedback%20Form%20Submission

Here's what they mean

Param Name Meaning Value
v Version 1
t Type event
tid Tracking ID (Your Tracking ID)
cid Client ID (Your GA Client ID)
ec Event Category Console
ea Event Action Submit
el Event Label Feedback%20Form%20Submission

Note, that the last 3 params ec,ea and el are the same ones which you would put in the JS code snippet. Only here, you have to URL encode their values.



Icon For Arrow-up
Comments

Post a comment