Get Country and City Name Using IP Address in PHP

You have generally seen that when you access some site, it show your location. This location on-site is retrieved by the IP address of visitors.

I have also required this concept in my own project and decide to write the snippet.

In this tutorial, you will see how to retrieve the country name and City name of the visitor through IP Address.

Here I have written a small snippet to get visitor address information.

You can see the demo which is shown below:

Get Country and City From IP - PHPCluster
Get Country and City From IP – PHPCluster

Demo

Let us see the given below snippet to understand how to get address detail by IP. Given below is the PHP code by which we are retrieving Country and City names from IP using Gelocation.net site.

PHP

<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
/*Getting user IP address details with geoplugin.net*/
$addr_details = @unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip_address));
$city = $addr_details['geoplugin_city'];
$countrycode = $addr_details['geoplugin_countryCode'];
$country = $addr_details['geoplugin_countryName'];
 echo "<b>"."City Name:"."</b>".$city."<br>";
echo "<b>"."Country Code:"."</b>".$countrycode."<br>";
echo "<b>"."Country Name:"."</b>".$country."<br>";
?>

Also Read: Get Geolocation from IP Address Using PHP

If you liked this tutorial, don’t forget to share it on social media. If you have any queries, write in the given below comment section.

Leave a Comment