Cibul Tech Blog - Fiddling with PHP, javascript and things

Posts Tagged ‘ubuntu’

Install Maxmind’s GeoIP IP database on Ubuntu for PHP

Tuesday, October 19th, 2010

Maxmind 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):

wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.6.tar.gz

Decompress it: tar -xvzf GeoIP-1.4.6.tar.gz and go into the folder to type the following:

sudo ./configure
sudo make
sudo make check
sudo make install

Download the latest PHP extension (today its here)

Decompress it, go in the geoip folder and type

sudo phpize
sudo ./configure
sudo make
sudo make install

Add the following line in your php.ini file used by apache (in my case: /etc/php5/apache2/php.ini): extension=geoip.so

To see if things have been working well until now, create a php test web page. We’ll make it prettier later on.

<html>
  <head>
    <title>Testing Maxmind GeoLite</title>
  </head>
  <body>
    <?php echo var_dump(geoip_db_get_all_info()) ?>
  </body>
</html>

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:

$ip_location = geoip_record_by_name($_SERVER['REMOTE_ADDR']);
$ip_location['latitude'];
$ip_location['longitude'];

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:

<html>
  <head>
    <title>Testing Maxmind GeoLite</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    <?php $ip_location = geoip_record_by_name($_SERVER['REMOTE_ADDR']); ?>
   
    var initialize = function(){

      var map = new google.maps.Map(document.getElementById("map"),{
        zoom: 13,
        center: new google.maps.LatLng(<?php echo $ip_location['latitude'] ?>,<?php echo $ip_location['longitude'] ?>),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

    }

    </script>
  </head>
  <body onload="initialize()">
    <h1>IP Geolocation with Maxmind</h1>
    <div id="map" style="width:300px; height:300px; margin: 10px;"></div>
  </body>
</html>

Things should be working now.

Tags: , ,
Posted in Geolocation | 3 Comments »