Getting visitor location in PHP.


I had been trying to track the location of visitors based on their IP addresses. I ran into problems earlier while trying to acheive that and gave up. Today, I Finally managed to do that. Thanks to the geodb availablehere. I hacked up a function that would accept an IP address as a parameter and return an array with location info.

The code for the function is:


function getIpInfo($ip){
$ipa=explode(".",$ip);
$ipnum=256*256*256*$ipa[0]+256*256*$ipa[1]+256*$ipa[2]+$ipa[3];
 //download the Geo DB file from http://software77.net/geoip-software.htm
$handle = fopen("IpToCountry.txt", "r");
$userinfo=NULL;
while (!feof($handle)){
 list ($start, $finish, $a1,$a2,$a3,$a4,$a5) = explode("t",fgets($handle));
   if(($start<=$ipnum)&&($ipnum<=$finish)) {$userinfo=array($a3,$a4,$a5); break; }
}
fclose($handle);
if(!$userinfo) $userinfo=array('Cannot Trace the Ip address','Cannot Trace the Ip address','Cannot Trace the Ip address');
return $userinfo;
}

One just needs to change the name of the file (in my case 'IpToCountry.txt') to the one that they have downloaded.The array returns ('2 Digit Country Code', '3 Digit Country Code', 'Full Country Name'), and, you can use it to display location or use it in your script as a variable. Make sure you do ip validation befor passing the IP address (ip2long()). A demo of it is available here. For a list of Other PHP/Javascript Demos please go to here.


Leave a Reply

Your email address will not be published. Required fields are marked *