Have you noticed how some websites automatically identify your location and country and refresh with information that is specific to that country? For example, google.com will always change the domain to google.ca for Canadians or google.lk if you are in Sri Lanka.
This can be a welcome feature in some cases as it eliminates the need for the user to manually select their location in order to find a product. The technology and the code behind this feature is no secret nor is it complicated. By simply querying a geolocation database with an IP (Internet Protocol) address will yield the desired results.
The ISP (Internet Service Provider) assigns an IP address to any computer that accesses the Internet, a unique address assigned only to the particular computer.
Every IP address can be used determine geographic information. Region, Cuty, Country and a whole lot more can all be gleaned from the IP address.
While deciphering and putting the information to good use does have its benefits, it can sometimes annoy the user. For example if someone who intends to travel from country A to country B and plans ahead to purchase a product from country B, being re-directed to their own country’s website would prove frustrating. So give some thought to the matter before employing the code and even consider having links to the other geo-location based sites as an option.
If you wish to try out the code for yourself, this code returns the country from an IP address.
< ? php
function get_ip_location($ip) {
// Querying the database
$NetGeoURL = “http://geotool.flagfox.net/?ip=”.$ip;
if($NetGeoFP = fopen($NetGeoURL,r))
{
ob_start();
fpassthru($NetGeoFP);
$NetGeoHTML = ob_get_contents();
ob_end_clean();
fclose($NetGeoFP);
}
preg_match (“/wiki(.*)/i”, $NetGeoHTML, $temp) or die(“Could not find element LAT”);
$location[0] = $temp[0];
return $location;
}
$ip = $_SERVER[‘REMOTE_ADDR’];
$location = get_ip_location($ip);
$remote_location = substr($location[0], strpos($location[0], ”)+3, -8);
echo ‘My location is ‘. $remote_location. ‘.’;
? >