geoip_iconHow to get the surfers country using PHP? Most coders need to tackle this problem sooner or later. There are several options out there. There is even a package called GeoIP Location. However, since this does not come with most default installations, it may not be your best choice.

A company called Maxmind specializes in professional GeoIP solutions. However, when you dig through their website, you can find that they also provide some free databases and free code. I will show you how to use this free stuff in a portable way to easily and quickly add an Ip to Country lookup feature to your PHP script in 2 easy steps.

Step 1. Download database and PHP file

Step 2. The Code

First, include the library and open the geoip database:

// include the php script
include("geoip.inc");

// open the geoip database
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);

Getting the country code:

// to get country code
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
echo "Your country code is: $country_code \n";

Getting the country name:

// to get country name
$country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']);
echo "Your country name is: $country_name \n";

And finally, close the geoip database:

// close the database
geoip_close($gi);

This solution uses a very fast and compact binary file as the database, and it does not add any to load to your MySQL server. You can do thousands of lookups per second on very average hardware with this code.