Sometimes you just need to know what country your site visitors are coming from—for example, if you’re trying to implement geo-targeted advertising. This article will show you how.
Sometimes you just need to know what country your site visitors are coming from—for example, if you’re trying to implement geo-targeted advertising. That’s where a tool like MaxMind’s GeoIP comes in—it lets you easily extract geographic data from your visitor’s IP address.
MaxMind makes available both commercial and free databases; the commercial ones are extremely precise and can get as fine-grained as the user’s city, while the free version can only identify the country of origin. We’ll use the free version in this article. If you need more detailed information, such as the remote client’s city and state of origin, you will need to purchase a more detailed database from MaxMind.
To use it, you’ll have to first download the GeoIP Free Country file and extract it into a directory in your Web server. Then you’ll have to pick which language API to use with the database file. For simplicity, we’re going to use the pure PHP version because it doesn’t require any additional configuration or Apache modules. Remember to read the license terms before installing these on your Web site to ensure you are in compliance.
The code below demonstrates the basics of using the module (geoip.inc) to access the GeoIP Free Country database (GeoIP.dat). The example assumes both the PHP include and the country database file are in the same directory as the PHP file itself. You’ll have to change the paths as needed if this is not the case in your installation.
// include functions
// read GeoIP database
$handle = geoip_open("GeoIP.dat", GEOIP_STANDARD);
// map IP to country
echo "IP address 18.104.22.168 located in " . geoip_country_name_by_addr($handle, "22.214.171.124") . " (country code " . geoip_country_code_by_addr($handle, "126.96.36.199") . ")";
// close database handler
// print compulsory license notice
echo "<p> -- This product includes GeoIP data created by MaxMind, available from http://maxmind.com/ --";
The sample code is pretty straightforward. After including the GeoIP PHP function library, the first step is to open the GeoIP database file with the geoip_open() function. This function accepts two arguments: the path to the database file and the type of database.
We then use the handle returned by the call to geoip_open() to obtain the two-letter country code and human-friendly name corresponding to the given IP address, via the geoip_country_code_by_addr() and geoip_country_code_by_name() functions, respectively. Both functions accept two arguments: the handle returned by geoip_open() and the IP address to resolve.
Once the required information is obtained, we close the database file with a call to geoip_close(). Simple as that.