The PHP GeoIP library makes it easy to look up country codes and names from an IP address. It’s not enabled/installed by default so you need to install it before you can access these functions. I’ve already posted about how to do this with Debian and other Linux distros will be similar.
Get a country code from an IP address
There are two functions for getting a country code from an IP address: one returns a 2 letter country code and the other a 3 letter country code. To get the country code for a specific IP address just pass it as the only parameter. The examples below use the IP address of my office.
echo geoip_country_code_by_name('18.104.22.168'); echo geoip_country_code3_by_name('22.214.171.124');
The first example would echo "NZ" and the second "NZL" because my office is in New Zealand.
To get the country code for the current visitor’s IP address use the following:
echo geoip_country_code_by_name($_SERVER['REMOTE_ADDR']); echo geoip_country_code3_by_name($_SERVER['REMOTE_ADDR']);
Get a country name from an IP address
The geoip_country_name_by_name() function does the same as the above but returns the country’s name. For example:
The above would echo out "New Zealand".
And the example using REMOTE_ADDR:
A note aboute REMOTE_ADDR
Note that using REMOTE_ADDR is not entirely reliable as it may be the IP address of a proxy server. You can use $_SERVER[‘HTTP_X_FORWARDED_FOR’] if it is set instead which should solve this issue some of the time if the visitor is connecting via a proxy.