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.


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.

  1. Download the GeoIP data file:
    % wget -O /tmp/geoip.gz
  2. Install GeoIP data file:
    % sudo mkdir /usr/local/share/GeoIP
    % cd /usr/local/share/GeoIP
    % sudo gunzip /tmp/geoip.gz
  3. Install PHP functions:
    % sudo apt-get install php-geoip
  4. 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

Example Code

  • Example #1 Below is sample php code to display your IP address and 2-digit country code:
       $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:
       $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" >';