Four free Geolocation Methods

Geolocation or Geo-Targeting is a method of identifying a visitor’s location in the world. You can use this information for anything as simple as greeting a visitor in their native language to automatically redirecting visitors to valid affiliate offers for the visiting demographic. This article takes a look at four different services that offer geolocation for free. This article will focus primarily on retrieving the visitor’s country code.

Maxmind GeoLite Country

Touting a 99.5% data accuracy is the GeoLite Country database allowing you to lookup a visitor’s country locally on your server. The database file is updated at the first of each month. The benefit with a local binary database is that lookups are performed right at the server and as a result may be faster and easier to cache than hitting a remote server you have no control over. However performing a large number of queries maybe cause some strain on your server if you have a cheaper machine or use shared hosting.

The easiest way to use the GeoLite country database is to download the binary format along with the file from the Maxmind PHP API. Once the GeoIP.dat and files are uploaded onto the server, the following PHP code will retrieve the visitor’s country code.

$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$addr = $_SERVER["REMOTE_ADDR"];
$country_code = geoip_country_code_by_addr($gi, $addr);	

Other APIs include C, Perl, Javascript, Python, C#, Ruby and Java examples, as well as an Apache Module and Microsoft COM Objects.


One of the more flexible remote service is This one provides the most information from a single line PHP code, but requires a connection to the server for every request (I recommend caching or using cookies for repeat visitors).

PHP Example:

$fetch = unserialize(fetch_url(''.$_SERVER['REMOTE_ADDR']));
$geo_code = $fetch['geoplugin_countryCode'];

You can also easily grab the city name using the ‘geoplugin_city’ key in the returned array. Other options supported are Javascript, JSON and XML . offers the simplest way to retreive a country code for a given IP address.

$geo_code = trim(fetch_url("".$_SERVER['REMOTE_ADDR']));
While not as straight forward as HostIP or GeoPlugin, provides a backup server in the event the first request fails.

$fetch = fetch_url("".$_SERVER['REMOTE_ADDR']."&output=xml");
	$fetch = fetch_url("".$_SERVER['REMOTE_ADDR']."&output=xml");
$fetchb = new SimpleXMLElement($fetch);
if (!$fetchb) 
	$geo_code = "";
	$geo_code = $fetchb->CountryCode;

There you have it, four different geolocation services, depending on your needs some may perform better than others, for high traffic sites the Maxmind solution is likely the best one short of paying for a monthly service.

Comments are closed.