IP Address to Country Lookup using iPInfoDB

By Akbar

Recently, I have been working on a simple idea, and that’s to show the Google GeoMaps (similar to the maps in Google Analytic) to show the different user activity directly on the site e.g. total number of downloads of a product by country, total subtitles translation, etc. My first research was to find some API which can draw decent looking graphs, as in Google Analytic, without considerable effort. Fortunately, I found that there is API from the Google which does exactly this:

Google GeoMaps

The next research task was to find a free and easy to use API which can provide the user location (City, Country, etc) given an API Address. While there are dozens such available, after trying few, I decided to go with the iPInfoDB API:
http://ipinfodb.com/ip_location_api.php

They have simple to use API, and also have sample PHP code on how to best use their service on the above API page. However, I ,after doing some research, ended up using the following code to fetch the user info from the IP Address:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Find the Country Name, Code and City information from the IPInfoDB:
// http://www.ipinfodb.com/ip_location_api_json.php
private function getGeoLocation()
{
	// Make a special cookie name by adding the IP address (to make different cookie per IP address)
	$cookieName = 'geolocation_'. str_replace('.', '_', $_SERVER['REMOTE_ADDR']);
 
	//Check if geolocation cookie exists (to avoid repeated calls to their server)
	if(!isset($_COOKIE[$cookieName]))
	{
		// If no, create a new request;
		$APIKey='{YOU-API-KEY}';
		$JSONUrl='http://api.ipinfodb.com/v3/ip-city/?key='.$APIKey.'&ip='.$_SERVER['REMOTE_ADDR'].'&format=json';
 
		// Get the JSON content from the remote URL
		$response = file_get_contents($JSONUrl);
 
		// Parse JSON
		$visitorGeolocation  = json_decode($response, true);
 
		// Geo Location query was successfull
		if ($visitorGeolocation && $visitorGeolocation['statusCode'] == 'OK') {
			$data = base64_encode(serialize($visitorGeolocation));
			setcookie($cookieName, $data, time()+3600*24*7); //set cookie for 1 week
		}
	}
	else
	{
		// Load previously stored info from the cooki
		$visitorGeolocation = unserialize(base64_decode($_COOKIE[$cookieName]));
	}
 
	return $visitorGeolocation;
}

This simple script also makes use of cookies to avoid sending repeated hits to their server if you have already found out the location of the user once. The two little tweaks I done to the code available at their API page are:

1) Make sure to add the user API Address in the cookie name. This helps detect the correct location for the user, even when he switches to different network within seven days.

2) I decided to use JSON fetch to get the results instead of using their wrapper class. This makes the overall code simple and clean.

With all this, I also ended up creating a simple product in the PHP which can be used to log and show the nice statistics graph on any website. I may make it available for public download soon. So, stay tuned.

Tags: , ,