Hello friends,
In this post i have mentioned code to get current location of user of website.
First of all you have to fetch IP Address of user, use below code.
$_SERVER['REMOTE_ADDR']
Using this you will get IP address of user.
You have to make one class file.Below is code for it. Just copy and past it and make on class file named ip2locationlite.class.php
<?php
final class ip2location_lite{
protected $errors = array();
protected $service = 'api.ipinfodb.com';
protected $version = 'v3';
protected $apiKey = '111f531eafecfdbb35f990fcdaac5ce4023309b67a4065dd09c7481e40b63c0f';
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;
}
}
?>
Now make one php page and write below code in it.
<?php
include('ip2locationlite.class.php');
//Load the class
$ipLite = new ip2location_lite;
$ipLite->setKey('111f531eafecfdbb35f990fcdaac5ce4023309b67a4065dd09c7481e40b63c0f');
//Get errors and locations
$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
print_r($locations);
?>
You will get array by this code. Array will contain status Code, status Message, ip Address, countryName, regionName, cityName, zipCode, latitude, longitude and time Zone.
If you want to access particular information like only city name, you have to pass key in array location. So your code will look like below.
for state code : $location['statusCode']
for status message : $location['statusMessage']
for ip address : $location['ipAddress']
for country code : $location['countryCode']
for country name : $location['countryName']
for state name : $location['regionName']
for city name : $location['cityName']
for zip code : $location['zipCode']
for latitude : $location['latitude']
for longitude : $location['longitude']
for time zone : $location['timeZone']
I hope this will helpful to you.