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 in Listing A 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.
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.