Implementing custom IP to Location/Country functionality in Drupal 6

There are several modules available that provide IP to location lookup, but sometimes you just have to write your own.

Take the easy way out

Before we get into this you should be aware there are several Drupal modules that offer this kind of functionality:

No? OK, lets do it the hard way

This being the case some times you run across a spec that may not quite match up with what's offered by currently available modules (happens all the time).

I'll take API for $500, Alex

There are freely available databases of IP to Country data available, however I personally prefer using an external lookup when available since there's no initial setup cost and I don't have to bother with database prefixing or switching the active db to do a lookup.

In this post I will be using ipinfodb.com's basic API do do IP to location lookups. This service comes in two flavors, full and basic. The basic service does a simple country lookup while the full lookup drills down to the region and city level.

Let's take a quick look at the basic API and some code that uses it to do lookups:

Basic API

http://ipinfodb.com/ip_query_country.php?ip=74.125.45.100

Output:

<Response>
	<Ip>74.125.45.100</Ip>
	<Status>OK</Status>
	<CountryCode>US</CountryCode>
	<CountryName>United States</CountryName>
</Response>

Example code:

   $query = 'http://ipinfodb.com/ip_query_country.php?ip=' . $item_ip;
   $resp = simplexml_load_file($query);
   $country_name = $resp->CountryName;
   $country_code = $resp->CountryCode;

It doesn't get much simpler than that. For extra credit you can (should) cache the current IP and country data locally to cut down on the number of duplicate lookups.

Freeman on web stuff

If it's wrong, bad or
stupid, let me just say that
I am not surprised.

- author unknown

User login

Navigation

More Drupal hotness

Powered by Drupal, an open source content management system