<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=278116885016877&amp;ev=PageView&amp;noscript=1">

, , , ,

Nov 2, 2021 | 1 Minute Read

How To Use The Drupal Google Analytics Module To Track IP Addresses

Table of Contents

Introduction

IP address tracking is important when you need to recognize returning visitors, track unique user activity on e-commerce websites, and so on.

It is surprisingly tricky to track IP addresses in the Drupal Google Analytics module because of the way in which JavaScript is handled. The custom dimension has to be set right after the tracker is created in the Google Analytics module, and right before it is being sent, i.e., after ga('create', 'UA-XXXXX-Y', 'auto'); and before ga('send', 'pageview').

The IP address can be found at the REMOTE_ADDR header. i.e., $SERVER[“REMOTE_ADDR”] in PHP. The IP address is almost always correct if the visitor is not using a proxy, or if the website isn’t using a caching system like Varnish or Boost Cache. So it’s always safer to use the X-Forwarded-For (XFF) HTTP header field.

Include the following in the hook_boot of your custom module:

<?php

/**

* Implements hook_init.

* Adds cookie all pages to return IP.

*/

function ics_analytics_boot() {

 if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

   if (strpos($_SERVER["HTTP_X_FORWARDED_FOR"], ',') !== false) {

     // Separate client IP from proxies' IP

     // Format is in [X-Forwarded-For: client, proxy1, proxy2, ..]

     $ips = explode (',', $_SERVER["HTTP_X_FORWARDED_FOR"]);

     $ip = trim($ips[0]);

   }

   else {

     // There is no comma in the value; we use it as is.

     $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];

   }

 }

 else {

   // Client is not using a proxy; we use the default REMOTE_ADDR.

   $ip = $_SERVER["REMOTE_ADDR"];

 }

 

 // Check if IP in cookie is already saved and not changed.

 if (!isset($_COOKIE['Drupal.visitor.track_ip']) || $_COOKIE['Drupal.visitor.track_ip'] != $ip) {

   // We set the cookie directly.

   setrawcookie('visitor_ip', rawurlencode($ip), REQUEST_TIME + 31536000, '/');

 }

}

Now, a cookie will be set on every page visit, which can be tracked by Google Analytics. The Drupal Google Analytics module provides a very extensive configuration page (admin/config/system/googleanalytics) for various ways to send custom dimensions and variables, and code that can be added before or after tracker creation and/or the ga send command. In our case, we have to add the following code in the section Custom Javascript code > Code snippet (before).

   try {

     ga("set", "dimension1", jQuery.cookie("visitor_ip"));

   }

   catch (e) {}

Now you should be able to track the IP addresses of your website visitors.

Do leave a comment below if you found this blog helpful or if you have any questions.

About the Author
Abhai Sasidharan, Axelerant Alumni
About the Author

Abhai Sasidharan, Axelerant Alumni


Back to Top