PHP location based on IP

PHP Why do you need your client IP?

When you manage your website and you may want to keep on eye on the people access to it (for security log, personnal tracking,...). One easy and efficient way, is to use their IP adress even if you user can change/hide it, it is still a good proxy to have a rough idea where is coming from.

How to get your client IP

In php it is super easy, you can access to this information juste with the following line:

<?php 
$ip = $_SERVER['REMOTE_ADDR'];
echo 'Your IP is: '.$ip;
?>

Locate this IP

Then the tricky question is, where this IP come from? You can find a lot of website which will track this IP back to the user location. Personnaly I use ipinfo.io. They will provide you at least the hostname, the geolocation, the network owner. To do that in PHP, you just need to extract their JSON answer like this:

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$location = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));

echo 'IP: '                      .$location->ip;
echo '<br/>Hostname: '           .$location->hostname;
echo '<br/>Geographic location: '.$location->loc;
echo '<br/>Network provider: '   .$location->org;
echo '<br/>City: '               .$location->city;
echo '<br/>Region: '             .$location->region;
echo '<br/>Country: '            .$location->country;
?>