Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sdeering/e331cee224e7d3e1f21697a7a17c9230 to your computer and use it in GitHub Desktop.
Save sdeering/e331cee224e7d3e1f21697a7a17c9230 to your computer and use it in GitHub Desktop.
/**
* 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