How to find the city and country of the visitor using PHP

Topics focus on Web Developments, Programming, Database, Digital Marketing Tutorials, Code Snippets, SEO, Social Media Marketing and Inspirational articles.

How to find the city and country of the visitor using PHP

How to find the city and country of the visitor using PHP

How to find the city and country of the visitor using PHP.

Sometimes we need to manage the content or currency based on the visitor’s country. Usually this situation arises to every developer, they try to find a better solution.

I introduce a new Application by which we can get the following information

IP address
Country Code(Ex: IN)
Country Name
State/Province/Region
City
Zip or postal code
Latitude
Longitude
Time Zone
Achieving this with IPInfoDB is very easy, providing an API for this.
Steps:

First register for an API at http://ipinfodb.com/register.php
Get an API key after activating your account
Download the files
Update your API key at line number 4
Then you get all the above info.
Or use the following code.

1
<!--?php  $ip=$_SERVER['REMOTE_ADDR']; $url="http://api.ipinfodb.com/v3/ip-city/?key=API_KEY_HERE&#038;ip=$ip&#038;format=json";     $ch=curl_init();     $timeout=0;     curl_setopt($ch, CURLOPT_URL,$url);     curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);     curl_setopt($ch, CURLOPT_USERAGENT , “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)”);     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);     $rawdata=curl_exec($ch);     $assocArray= json_decode($rawdata,true);     curl_close($ch); ?-->

The array $assocArray will give the above info. for example

1
<!--?php echo $assocArray['cityName']; ?-->

will print the City name.
Here we are executing and parsing the URL with PHP, don’t you know this? read the article How to execute a URL in PHP
Usage:
Sometimes we need to change the flag or Logo as per the country, then think about following lines of code

1
2
3
4
5
6
7
8
9
&lt;!--?php 
if($assocArray['countryName'] == 'INDIA')
{
    echo "<img alt="" />";
}
else{
    echo "<img alt="" />";
}
? &gt;

Add comment


 

Pin It on Pinterest

Share This