Lately, I've had the need to install a geolocation database on a web server to localize (as closely as possible) a visitor based on its IP address.
For this, I've been using the MaxMind geolocation database. Although Maxmind is a commercial service, they provide a free database mapping IPs to countries. Maxmind provides a PHP geoip extension enabling a very quick access to the GeoIp database.
In this blog article, I'll describe all the required steps to install the geoip extension on a PHP server, on a CentOS distribution.
First, a quick note about Debian/Ubuntu user. They have the chance to have a nice package installed. So installing the module is as simple is typing:
apt-get install php5-geoip
First step: downloading the GeoIP databases
You must download the database mapping IP addresses to locations.
Maxmind provides a free database mapping IP addresses to countries.
It can be downloaded at the GeoLite Coutry database download page.
If you have a Maxmind account, you can download your databases in your account page.
Maxmind provides files in many formats. You must download the file in the "Binary format for APIs".
Note: if you are working on a remote server through SSH, lynx can be useful to download the files:
yum install lynx lynx http://www.maxmind.com/app/download_files
Step 2: Uncompress the files
You should uncompress the files in the directory /var/lib/GeoIP.
At the end of this operation, there should be one or many ".dat" files into the /var/lib/GeoIP directory.
Step 3: Configure the context
This step is needed only if SELinux is enabled on your system.
SELinux is a security mechanism that will prevent Apache to access the geolocalisation database if it is not explicitly allowed to.
In order to grant access to the Geolocalisation database, use these commands:
chcon -t httpd\_sys\_content_t /var/lib/GeoIP chcon -t httpd\_sys\_content_t /var/lib/GeoIP/* chcon system\_u:object\_r:textrel\_shlib\_t /usr/lib/php/modules/geoip.so
Step 4: Enable the GeoIP PECL module
The geoip PHP extension is a PECL module.
The PECL module has a dependency on the geoip C library that must be installed:
yum install GeoIP GeoIP-devel
If PECL is not installed, you must install it on the server:
yum install php-pear php-devel httpd-devel
Then, you can start retrieving and compiling the module:
pecl install geoip
Finally, you must tell PHP to load the extension. On CentOS, we can do that by adding a file in the /etc/php.d directory:
In this file, just add this line:
Finally, just restart Apache:
About the author
David is CTO and co-founder of TheCodingMachine and WorkAdventure. He is the co-editor of PSR-11, the standard that provides interoperability between dependency injection containers. He is also the lead developper of GraphQLite, a framework-agnostic PHP library to implement a GraphQL API easily.