Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Send Google analytics tracking event.
*
* @param mixed $action
* Event action.
*/
public function sendGoogleTrackingEvent($action) {
if (!$this->isProduction()) return;
$googleAnalyticsUA = 'UA-XXXXXXXX-XX';
// phpcs:disable
$data = [
'v' => 1,
't' => 'event',
'tid' => $googleAnalyticsUA,
'cid' => \Drupal::service('uuid')->generate(),
'ec' => 'Category name',
'ea' => 'Action name,
'el' => 'Label name',
'uip' => \Drupal::request()->getClientIp(),
'ua' => $_SERVER['HTTP_USER_AGENT'],
];
// phpcs:enable
$url = 'https://www.google-analytics.com/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($ch);
curl_close($ch);
}
/**
* Check if app is running in production.
*/
public function isProduction() {
return (strpos($_SERVER['HTTP_HOST'], 'production.com') !== FALSE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.