Friday, December 14, 2012
Finding geo location of the ip address in PHP
If you are using google map in your application and wanted to show the user location google map in your application. then we the find the ip address and get the geo location of the ip address. Bellow is the method to find the city by passing the ip address Using PHP.
/**
* Funtion to find the city by passing the IP Address.
*/
function geoCheckIP($ip)
{
//check, if the provided ip is valid
if (!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}
//contact ip-server
$response = @file_get_contents('http://www.netip.de/search?query=' . $ip);
if (empty($response))
{
throw new InvalidArgumentException("Error contacting Geo-IP-Server");
}
//Array containing all regex-patterns necessary to extract ip-geoinfo from page
$patterns = array();
$patterns["town"] = '#City: (.*?)<br#i';
//Array where results will be stored
$ipInfo = array();
//check response from ipserver for above patterns
foreach ($patterns as $key => $pattern)
{
//store the result in array
$ipInfo[$key] = preg_match($pattern, $response, $value) && !empty($value[1]) ? $value[1] : 'not found';
}
/* I've included the substr function for Country to exclude the abbreviation (UK, US, etc..)
To use the country abbreviation, simply modify the substr statement to:
substr($ipInfo["country"], 0, 3)
*/
$ipdata = $ipInfo["town"];
return $ipdata;
}
geoCheckIP('50.56.112.226');
For more dinformation and send me comments.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment