Geolocating with Maxmind Geoip PHP API
Whenever geolocation feature is required in any of my projects, my first choice is IP2Location. But recently one of my clients insisted on using Maxmind's GeoIP feature for this purpose and I got a chance to explore yet another way in PHP of finding user's geographic location based on the IP address.
Maxmind provides a wide range of API for almost all the major programming languages. It also has an Apache module for using the GeoIP feature directly in your applications .htaccess file. For PHP, Maxmind offers 3 ways to query the GeoIP database -
- Pure PHP module - No installation required. No dependencies.
- PHP extension on PECL
- And mod_geoip with PHP
Refer to GeoIP PHP API on Maxmind for details of each one.
If you are on a Debian system like me, installing GeoIP is just a matter of issuing one command.
-
aditya@aditya:~$ sudo apt-get install php5-geoip
But only installing the geoip package is not enough. You also need to get the geoip database from Maxmind. They offer free as well as paid versions of their IP databases. The City and Country databases are available for free.
Download, unpack and put them in /usr/share/GeoIP on your system. This is the place where geoip functions will look for the necessary database files. Also, remember that you will have to rename GeoLiteCity.dat to GeoCity.dat before you can start using the city database.
You can now run a simple PHP script as follows to verify whether everything is setup correctly and the databases you have downloaded are available for use.
The available flag should be set for all the databases that you downloaded. That's it. You are now set to detect your user's location. Following is the code snippet that can be used to get all geographic information of your user based on their IP address
There are lot of other functions that offers specific information like region, three character country code, etc. Refer the GeoIP section in PHP manual for details of those functions.
About this entry
You’re currently reading “ Geolocating with Maxmind Geoip PHP API ,” an entry on SANIsoft – PHP for E Biz
- Published:
- 3.15.10 / 9:34am
- Category:
- Geolocation, HowTo, PHP
- Author:
- Aditya Mooley
No comments
Jump to comment form | comments rss | trackback uri