One of our project requirement is to be able to track individual users, including guests. Tracking guest/anonymous users can be quite challenging considering the different possible scenarios.

The easiest scenario is when the browser supports cookies, in such case, just assign a unique ID as a cookie and retrieve the cookie everytime access is made. The basic concept is to create an ID that will not likely be duplicated in any user. So, in our case, we used IP Address + User Agent + Forwarded For + Time + Random number. That should create unique ID for anybody accessing the site anywhere and anytime in the world.

The second scenario is when the browser doesn’t support cookies. This is more involved because we need to assign an ID unique and consistent for a specific user. In this case, we used IP Address + User Agent + Forwarded For. There are some pitfalls with this approach, such as when user changes internet connection on a DHCP network… but I guess that’s a bit of a technical limitation at the moment.

In any case, below is the code snippet used to create the unique ID key, the solution below is a combination of PHP and Javascript codes:

<?php
$IP =’none’;
//let’s try to get original IP
if ($IP = getenv(’HTTP_CLIENT_IP’)) {}
else if ($IP = getenv(’HTTP_X_FORWARDED_FOR’)) {}
else if ($IP = getenv(’HTTP_X_FORWARDED’)) {}
else if ($IP = getenv(’HTTP_FORWARDED_FOR’)) {}
else if ($IP = getenv(’HTTP_FORWARDED’)) {};
$userKey = md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].$IP);
if (!isset($_COOKIE["unique_id"])) {
// below is the unique user key string
$time = time();
srand($time);
// could be new user, let’s set the cookie + some more text
setcookie(”unique_id”,$userKey.$time.rand(),$time+31356000);
}
?>
<script language=”javascript”>
var userKey = ‘<?php echo $userKey; ?>’;
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + “=”)
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(”;”,c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return “”
}
var unique_id = getCookie(’eb_unique_id’);
if (unique_id==”") unique_id = userKey;
alert(unique_id);
</script>

Leave a Reply