Friday, August 22, 2008

Obtaining a visitor’s country from its IP address

Sometimes, when you are building a site, you may want the content of the homepage or even the language to be used, to change depending on the country from which the visitor is accessing.

How can you do this? It’s actually pretty simple, just follow these steps:

1. Get an IP-Country database. Each row of these databases often has three columns: start and end range for the IP address and the country to which that range is associated (e.g. http://www.ip2location.com). Most of these databases are not free, and the ones that are, are generally a little outdated. I recommend purchasing a database, mainly because you can download a new updated version every month.

2. Import the IP-Country database into the database on your site. The IP-Country databases are generally in the .csv format (comma separted values), so you have to execute a query to import all the values. That query should look something like this:


LOAD DATA LOCAL INFILE '/ip-country.csv'
INTO TABLE ip_country
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(start_range, end_range, country);

3. Include the following PHP code on the page that you want to use to obtain the Country:

$IPaddr = "";
if (getenv("HTTP_X_FORWARDED_FOR")) {
$IPaddr = getenv("HTTP_X_FORWARDED_FOR");
} else {
$IPaddr = getenv("REMOTE_ADDR");
}
$ips = split ("\.", "$IPaddr");
$ip_address = ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
$sql = "SELECT country FROM ".TBL_IP_TO_CITY." WHERE ".$ip." BETWEEN IP_FROM AND IP_TO";
$res = $db->query($sql);
$row = mysql_fetch_row($res)
$country = $row[‘country’];

That’s it! You can now obtain the name of the country from which you visitor is accessing from and display the appropriate content.

P.S: If you think Ip2Location.com is paying me for each database bought from this Blog, you are wrong!

P.S2: If you are working at Ip2Location.com, please consider paying me for all the referrals!

No comments: