HOWTO: Show city and country of the visitor in PHP | Flavio's blog
 

HOWTO: Show city and country of the visitor in PHP

I needed to automatically show the city and the country of origin of a visitor, to insert them automatically into the new Guestbook Site.

IPInfoDB.com offers a free geolocation, which enables, given the IP address of a visitor, of showing (as far as possible) some data, Latitude as, Longitude, Country, Time zone etc.. etc..

Obviously this service is free, contains inaccuracies due to the fact that often some old IP addresses are transferred to other providers, and until the database is not updated, there is the risk that the wrong results are shown.

Overall, however, seems to be a fairly reliable geolocation service (and certainly will miss a few kilometers from the city of, but not the Nation 🙂 )

First of all, must register on their site, and obtain the API key.

Create a PHP page with this code:

<?
// IP Address of the guest
$ip = $_SERVER['REMOTE_ADDR'];    
//echo "<b>IP Address= $ip</b><br />"; 
$your_key = 'YOUR API KEY';
$url = "http://api.ipinfodb.com/v3/ip-city/?key=$your_key&ip=$ip&format=json";

$data = json_decode(file_get_contents($url));

echo $guest_ip = ucwords(strtolower($data->cityName.', '.$data->countryname));
echo "<br />";
echo $ guest_ccode = $ data->countryCode;

?>

We substitute YOUR API KEY, API KEY obtained during the registration site.

We load the php file on the webserver, and throwing will get something like:

Naples, Italy
IT

that, in fact, corresponds to the origin of my IP address. 🙂

 

0 Comments »

Please accept third-party cookies to be able to comment on the post! The CHANGE COOKIE CHOICES button is located in the footer of the site. / In order to comment this post, please accept the third party cookies! The button CAMBIA LE SCELTE DEI COOKIE is in the footer of the website.