Tuesday Jun 16, 2009  0

IP to Country

I was asked earlier today to have several of my client’s websites to recognize the geographical location of his visitors to aid in his online sales. I’ve done a similar script before but with text files; Thankfully there is an open source resource of IP Addresses I can use for reference. MaxMind offers a CSV (Comma Separated Values) file of the data we need for free, which you can download here.

To implement this using PHP and MySQL, first you’ll need to create a table for the CSV data then import it. Below is the table I used:

CREATE TABLE IF NOT EXISTS `ip2country` (
  `ip_start` varchar(15) NOT NULL default '',
  `ip_end` varchar(15) NOT NULL default '',
  `int_start` int(10) unsigned NOT NULL default '0',
  `int_end` int(10) unsigned NOT NULL default '0',
  `country_code` char(2) NOT NULL default '',
  `country_name` varchar(50) NOT NULL default ''
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Once you’ve created the table you can then import the CSV data using PHPMyAdmin. I suggest putting the .csv file in a zip archive before uploading it to your server to lessen the upload time.

Below is a function I made to get the country code and country name form the database and return the result in an array:

function ip2country($ip) {
	if ($ip) {
		$query = mysql_query("SELECT country_code,country_name FROM ip2country WHERE INET_ATON('$ip') BETWEEN int_start AND int_end",$mysql); // look up IP address
		if (mysql_num_rows($query)) {
			$data = mysql_fetch_assoc($query);
			mysql_free_result($query);
			return array($data['country_code'],$data['country_name']);
		} else {
			return array("No result for $ip");
		}
	} else {
		return array("specify an IP Address");
	}
}

Here’s an example of the function:

$data = ip2country($_SERVER['REMOTE_ADDR']);
if (count($data) == 2) {
	echo "Country Code: $data[0] Country: $data[1]";
} else {
	echo $data[0];
}

You can extend the code further by displaying flags according to the country code. You can download the small collection I have of small flags in PNG format wrapped in a zip archive.

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Technorati
  • Twitter

Leave a Comment

Previous post:

Next post: