Pages

Tuesday, March 5, 2013

Web based IP geolocation lookup


Web based IP geolocation lookup

IP Geolocation is a technique to identify the subject party's IP address, then determines what country, state, city, ZIP Code, organization, or location the IP address has been assigned to. There are several IP geolocation providers in the industry supplying IP address databases. These databases contain IP address data which may be used in firewalls, domain name server, ad servers, routing, mail systems, web sites, and other automated systems where geolocation may be useful.


ip2locationlite.class.php
<?php
final class ip2location_lite{
protected $errors = array();
protected $service = 'api.ipinfodb.com';
protected $version = 'v3';
protected $apiKey = '';

public function __construct(){}

public function __destruct(){}

public function setKey($key){
if(!empty($key)) $this->apiKey = $key;
}

public function getError(){
return implode("\n", $this->errors);
}

public function getCountry($host){
return $this->getResult($host, 'ip-country');
}

public function getCity($host){
return $this->getResult($host, 'ip-city');
}

private function getResult($host, $name){
$ip = @gethostbyname($host);

if(preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)){
$xml = @file_get_contents('http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');
if (get_magic_quotes_runtime()){
$xml = stripslashes($xml);
}

try{
$response = @new SimpleXMLElement($xml);

foreach($response as $field=>$value){
$result[(string)$field] = (string)$value;
}

return $result;
}
catch(Exception $e){
$this->errors[] = $e->getMessage();
return;
}
}

$this->errors[] = '"' . $host . '" is not a valid IP address or hostname.';
return;
}
}
?>

result.php
<?php
include('ip2locationlite.class.php');

//Load the class
$ipLite = new ip2location_lite;
$ipLite->setKey('API_KEY');
//To get API_KEY register using this link http://ipinfodb.com/register.php
//Get errors and locations
//$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
$errors = $ipLite->getError();

//Getting the result
echo "<pre>";
 print_r($locations);
echo "</pre>";
?>

After finished the setup run the result.php will get country value.

No comments:

Post a Comment