How To Locate Your Website Visitors Via IP

More and more websites are using a geolocation service to show advertisements and offers near a visitor’s location. Using such a service on your own website is quite easy. This post only focuses on using the MaxMind GeoIP City database based on IP addresses and using it with PHP because I have already implemented this solution on one of my websites and wanted to share this tutorial because I think it may be helpful for my visitors.

This tutorial requires that you are able to compile PHP extensions on your system which means that you must have root access to your server and need to be able to access it from the Linux command line.

Although the price you have to pay for the MaxMind database may appear high at first glance you may not need the full database but may just purchase a database for a single country – just as I purchased the German database only. There is also a free GeoLite City database available from MaxMind which has a worldwide coverage and has an accuracy of 79% for US cities.

There are just 6 simple steps for you to perform – I will cover using the German database on an Ubuntu Linux system only but only the file name is different with versions for other countries so you need to adjust some values in the examples below.

  1. Purchase and download the database (choose the API version, not the CSV file)
  2. Unpack the file and move the contents to the appropriate directories:
    tar -xvzf GeoIP-132de_20090901.tar.gz
    mkdir /usr/local/share/GeoIP
    mv GeoIP-132de_20090901/GeoIPCityde.dat /usr/local/share/GeoIP/GeoIPCity.dat
  3. Install the header files for the library:
    apt-get install libgeoip-dev
  4. Install the geoip extension for PHP:
    pecl install geoip

    If you’re getting an error like this

    checking for LGPL compatible GeoIP libs... wrong version
    configure: error: You need version 1.4.0 or higher of the C API

    you can fix this by downloading the C files directly from MaxMind and compiling them manually:

    tar -xvzf GeoIP-1.4.6.tar.gz
    cd GeoIP-1.4.6
    make check
    make install
    apt-get remove libgeoip-dev
    pecl install geoip
  5. Load the new PHP extension – add these lines to your php.ini:
  6. Restart your (Apache) web server

You can now use all of the PHP functions the geoip extension offers such as:

&lt;?php var_dump(<a href="" target="_blank">geoip_record_by_name</a>($_SERVER['REMOTE_ADDR'])); ?&gt;

In the next post I’ll cover using the GeoLocation object available in JavaScript in Firefox 3.5 and using it to get even more detailed locations.

Be Sociable, Share!


February 13th, 2010 at 1:55 pm

thanks man..! just googled it..! pretty nice tricks.!

December 10th, 2010 at 12:45 pm

Fantastic mini-tutorial. I`ve been wondering how to implement this to my website for a long time now. You saved me :).

Comments are closed.

Sascha Kimmel - Living The Web Experience Since 1996 by tricosmedia