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 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.
Using the geographic data
Now, what to do with this geographic knowledge? Well, one good use for geographic data is to target users with ads tailored to their country. Here's a simple example in PHP that uses a MySQL database to deliver geo-targeted ads.