I wanted an easy way to find my visitor’s ip address and location for my website. After some time digging, it turns out there are many ways you can do this. Specifically I came across this site which offers a few lines of code to find your visitors ip address. Although it’s a handy way to do it, it’s worth mentioning that it is not a full proof way to do it. If your visitor really wants to fool you he can. Here, I have made a function out of that code. You can use it in a module like way. You insert the function in a php file, and include that file in your source code.
function getRealIpAddr() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Next, I wanted to find the location of my visitor, based on the ip address I retrieved earlier. There are many geolocation services which offer an api for doing so. I did try many of them, but found ipinfodb to be the best free geolocation service from those I tried. When I say best, I mean ease of use and accuracy. I did have a minor problem signing up with them though. Their registration form seems to suffer from a not so well implemented captcha, but after several tries I managed to sign up and get my api key. In their website they have several examples on how to use their api in many programming languages. It’s very easy to do so and the documentation is helpful. Here is my function.
function getLocation($ip) {
$url="https://api.ipinfodb.com/v3/ip-city/?key=your_api_key&ip=".$ip."&format=json";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$status = $data['statusCode'];
$country = $data['countryName'];
$town = $data['regionName'];
$city = $data['cityName'];
if ( $status == 'OK' ) {
return "$city, $town, $country";
} else {
return "Something went wrong..";
}
}
You can request the result to be in xml or json. I use json here. I parse it to get only the relevant information I want. Your use might differ. I have placed both of these functions in a php file and included that file in my main script. For full source code visit my github page. I hope this might come handy to you some day. If you have any comments or suggestions please use the comments below.