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.
- Purchase and download the database (choose the API version, not the CSV file)
- Unpack the file and move the contents to the appropriate directories:
tar -xvzf GeoIP-132de_20090901.tar.gz
mv GeoIP-132de_20090901/GeoIPCityde.dat /usr/local/share/GeoIP/GeoIPCity.dat
- Install the header files for the library:
apt-get install libgeoip-dev
- Install the geoip extension for PHP:
pecl install geoip
If you’re getting an error like thischecking 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:wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.6.tar.gz
tar -xvzf GeoIP-1.4.6.tar.gz
apt-get remove libgeoip-dev
pecl install geoip
- Load the new PHP extension – add these lines to your php.ini:
- Restart your (Apache) web server
You can now use all of the PHP functions the geoip extension offers such as: