Where You At? Adding Simple Geo-targeting to Your Site

I am working on a site that needs to target 7 specific markets with unique content. I was looking for a simple way to target content by geographic location.

GeoPlugin.com has a simple API that makes it easy to plug geo-targeted content into your application or site. I was able to get started by playing with their examples.

Passing an IP address to their API returns some great information including:

  •  City
  • Region
  • Area Code
  • DMA Code
  • Country Code
  • Country Name
  • Longitude and Latitude
  • Currency info
In the case of my particular project, just getting that DMA code would allow me to figure out which broadcast market the user was in. Then I would be able to query content from WordPress based on where they were detected.
But let’s play with just displaying the city.
The first step is to get the info from the API:

$geo_lookup = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));

That gets an array with the data on the user’s IP address.

All I’m interested in this time is the city. The City is returned in the array with the key geoplugin_city.

$city = $geo_lookup['geoplugin_city'];
echo "Hello ".$city;

Here is the complete code: (all 3 lines)

$geo_lookup = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));
$city = $geo_lookup['geoplugin_city'];
echo "Hello ".$city;

You can see the code in action here >>

It’s certainly not foolproof. I tested this with a coworker who was connected to our home office by VPN. His Madison, WI laptop was detected in Saint Paul, MN.  But this at least allows us to make some content easier for a greater number of users.