Pages

Friday, September 14, 2012

To know country name, city name for website where they access


First you need to included the following class file.


<?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');

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;
}
}
?>

And, you can know the values by calling following file.

<?php
include_once('ip2locationlite.class.php');
//Set geolocation cookie
if(!$_COOKIE["geolocation"]){
  $ipLite = new ip2location_lite;
  $ipLite->setKey('27f627ceaa9ed0ba91b09b52e74aa47a6f51c8f2dea24dd6597c203a7a6602a8');
  $visitorGeolocation = $ipLite->getCountry($_SERVER['REMOTE_ADDR']);
  if ($visitorGeolocation['statusCode'] == 'OK') {
    $data = base64_encode(serialize($visitorGeolocation));
    setcookie("geolocation", $data, time()+3600*24*7); //set cookie for 1 week
  }
}else{
  $visitorGeolocation = unserialize(base64_decode($_COOKIE["geolocation"]));
}
// print_r($visitorGeolocation);
echo $country_name = $visitorGeolocation['countryName'];
//var_dump($visitorGeolocation);
?>

No comments:

Post a Comment