Geolocate your visitors with PHP (part 1)

In this short post I’ll show you how to geolocate your visitors with PHP. First of all let’s have a look at what you’ll need :

  • PEAR GeoIP
  • MaxMind GeoLite Country

Installing PEAR GeoIP

Using your console or using the command prompt type :

pear install http://download.pear.php.net/package/Net_GeoIP-1.0.0RC1.tgz

Obtaining MaxMind GeoLite Country

The database can be downloaded freely here. Download it and put it in the same folder where your script will reside.

The code

<?php
	require_once('Net/GeoIP.php');

	$geoip = Net_GeoIP::getInstance('./GeoIP.dat');
	$ip = getenv('REMOTE_ADDR');
	$country = $geoip->lookupCountryName($ip);

	echo "Hi, you're from ".$country;
?>

Walkthrough

Now let’s go through the lines of code. The first line tells us to include the GeoIP class, which we installed previously and then create a geoip object in line 5 from the database we downloaded.
Next, in line 6 we get the IP address of the visitor and finally we call the lookupCountryName method with the IP address as parameter in line 7 and it will return us the country.

The last line just outputs the country, for example, “Hi, you’re from Mauritius”. That’s it, now you know where your visitor’s from.

In the second part of this article I’ll show you how to use the script to visually map your visitors using Google Maps. You can have a little preview of the script here.

Be Sociable, Share!

Comments (5)

  1. 11:24 am, July 9, 2008Shah  / Reply

    This is cool & easily tweakable.
    Thanks for providing the info online.

    Here’s another one you may want to check out too. – http://www.ardamis.com/2008/01/27/how-to-geolocate-visitors-using-an-ip-to-country-database/

    Goodnight :)

  2. 2:26 am, July 19, 2008Omry  / Reply

    You can also use my IP2C library.
    it comes with a binary database file, and performance is excellent.

    http://firestats.cc/wiki/ip2c

  3. 11:24 am, July 19, 2008asvin  / Reply

    thnx for the tip Omry

  4. 12:44 pm, November 3, 2008Tim  / Reply

    We are not very well-versed in programming. Therefore, we are using the PHP API from the IP2Location.

    http://www.ip2location.com/php.aspx

  5. 8:46 am, July 18, 2010Aafrin  / Reply

    great tutorial, helps me a lot. thank you for it

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>