PHP Geo-IP Location in 4 lines

Want to look up IP addresses to a geographical location? Firstly, download maxmind_geoip.php and GeoIP binary database from MaxMind. I copied them to a universal location on a server so I can use it across applications.

require_once '/usr/local/share-php/maxmind_geoip.php';

$gi = geoip_open("/usr/local/share-php/GeoIP.dat",GEOIP_STANDARD);

$location = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);

There we go 4 lines.

$location will return the 2 letter ISO country code for that country, for you to do whatever you want with!

Why not combine it with the Flag Icon Set from Fam Fam Fam? Here's how I did it

<img src="images/flags/'.strtolower($location).'.png" alt="'.$location.'" title="'.$location.'" />
You could even use the PECL extenstion or the PEAR extenstion if you're feeling fancy.

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

3 thoughts on “PHP Geo-IP Location in 4 lines”

Leave a Reply

Your email address will not be published. Required fields are marked *