How to install Maxmind’s GeoIP on Ubuntu/Linux for PHP

provides a useful database and API for server side IP Geolocation. It is useful when you don’t want your server to hang on external services each time fetching a location from an IP address is needed. This posts goes through the installation process of the database with a PHP extension on an Ubuntu platform. I’m writing this for my own use. If it can be useful to you, yeepee.
See it working here. I’ll appreciate it if you can comment at the bottom of the page on how off from the result showed on the page is from your actual location.
Open a terminal
Download the C library in any location on your system (the latest as of today is here):

[cc lang=”php” tab_size=”2″ lines=”40″]
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.6.tar.gz
[/cc]
Decompress it:
tar -xvzf GeoIP-1.4.6.tar.gz
and go into the folder to type the following:
[cc lang=”php” tab_size=”2″ lines=”40″]
sudo ./configure
sudo make
sudo make check
sudo make install
[/cc]

Download the latest PHP extension (today its here)
Decompress it, go in the geoip folder and type
[cc lang=”php” tab_size=”2″ lines=”40″]
sudo phpize
sudo ./configure
sudo make
sudo make install
[/cc]
Add the following line in your php.ini file used by apache (in my case: /etc/php5/apache2/php.ini):
[cc lang=”php” tab_size=”2″ lines=”40″]
extension=geoip.so
[/cc]
To see if things have been working well until now, create a php test web page. We’ll make it prettier later on.
To complete the installation, unzip and set GeoLiteCity database in the folder indicated by the test page (here /usr/local/share/GeoIP/GeoIPCity.dat).
Once the database is downloaded and placed in the correct location, use the following functions to get the latitude or longitude from the ip address:

[cc lang=”php” tab_size=”2″ lines=”40″]
$ip_location = geoip_record_by_name($_SERVER[‘REMOTE_ADDR’]);
$ip_location[‘latitude’];
$ip_location[‘longitude’];
[/cc]
To wrap things up, the following code puts the retrieved latitude and longitude on a neat little google map. Paste this in your test page:
Things should be working now.

Tagged , , , ,

Leave a Reply