Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save kvantstudio/3732b55bfae5db38849f12ce9e5532d2 to your computer and use it in GitHub Desktop.

Select an option

Save kvantstudio/3732b55bfae5db38849f12ce9e5532d2 to your computer and use it in GitHub Desktop.

Revisions

  1. @sdeering sdeering created this gist Oct 30, 2019.
    49 changes: 49 additions & 0 deletions Drupal 8 Send Google Analytics Event from PHP Back-end
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    /**
    * 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);
    }

    }