PHP Code

PHP: Geolocation on IP Addresses

Any time I take information from a visitor/client/customer via the some type of form post (cart order, forum post, contact form, etc.) I usually log the IP address it came from. This is good information to have in case someone abuses your services and you need ban them but we can also use it to see where they are from. Geolocation with an IP address is an easy thing to accomplish in PHP and can shed some light on where your visitors/customers are coming from. You see it often in stat reporting software like Google Analytics but it’s very easy to add into your own web applications.

Find a Geolocation Service

There are many geolocation services out there that you can tap into with PHP, just search “php ip geolocation”. For this article I’m using IP Info DB who have a really simple free API to tap into.

Click here to see info about your IP. If you look at the source you can see it’s in XML format.

Here is a simple example of displaying the flag of the country where a visitor is from:


require_once( 'demos/gelocation/geolocation.class.php');

//Load the class (country precision)
$geolocation = new geolocation(false);
 
//Query timeout (in seconds) before switching to backup server
$geolocation->setTimeout(2);
 
//Set the IP to the visitor
$geolocation->setIP($_SERVER['REMOTE_ADDR']);
 
//Get errors and locations
$locations = $geolocation->getGeoLocation();

//Print out the country name and flag image based off the visitor IP
echo "You are are from " . $locations[0]['CountryName'] . " and  is your flag";

You are from and is your flag

This is a modified version of the sample code from IPInfoDB.

Resources

Whether to show aggregated visitor info on a map (Google Analytics), take you to a country or region specific version of a site (Groupon, many big online retailers) or send your current location to your friends via social media, geolocation is evident in many of todays popular web apps.

Continue Reading

  • dan

    I clicked the link which said ‘view information about your IP and this is what came up:

    0.0.0.0MOVED00000

    • Skye

      Looks like the IP Info DB requires an API key now. I’ll update shortly so it works again.