Installing PHP GeoIP on Ubuntu
This article based on the PHP GeoIP functions simply provides the steps necessary to get GeoIP working with PHP on Ubuntu systems.
Installation
To be able to utilise these functionality, both the PHP GeoIP functions files and the GeoCityLite.dat data file must be installed on your system.
- Download the GeoIP data file:
% wget -O /tmp/geoip.gz http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
- Install GeoIP data file:
% sudo mkdir /usr/local/share/GeoIP % cd /usr/local/share/GeoIP % sudo gunzip /tmp/geoip.gz
- Install PHP functions:
% sudo apt-get install php-geoip
- Restart apache webservers using one of the following:
- Ubuntu 15.04 and later
% sudo systemctl restart apache2
- Ubuntu 12.04 - 14.10
% sudo service apache2 restart
- Ubuntu 15.04 and later
Example Code
- Example #1
Below is sample php code to display your IP address and 2-digit country code:
<?php $ip_address = $_SERVER['REMOTE_ADDR']; $ip_country = geoip_country_code_by_name ($ip_address); echo $ip_address.', '.$ip_country; ?>
You can use other GEO data like City or ISP. Review the PHP GeoIP functions manual for more details. - Example #2
Sample code to display the country flag associated with the 2-digit country code:
<?php $ip_address = $_SERVER['REMOTE_ADDR']; $ip_country = geoip_country_code_by_name ($ip_address); $ip_flag = strtolower(geoip_country_code_by_name($ip_address)); echo '<img title="'.$ip_country." src="/flags/'.$ip_flag.'.png" >'; ?>
References
- PHP GeoIP functions @ http://php.net/manual/en/ref.geoip.php
- WikipediA ISO 3166-1 country codes @ https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
- ISO 3166-1 country flag icons @ www.famfamfam.com