How To Find Visitor Location(Country) In PHP

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. 

Here i am going to help you to find a visitors location or country using php programming language.

Visitor location is importand for blogger, cpa marketor ,company or anyone who want to show different content or product according to visitor  country.

I am using this in CPA marketing. this is really helping me in cpa marketing , i am using it to show different clickable link according to visitors country.

Lets Begin this tutorial.

At first you need to find a ip adress of visitor of your website using below code.

<?php
function getVisIpAddr() { 
      
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) { 
        return $_SERVER['HTTP_CLIENT_IP']; 
    } 
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
        return $_SERVER['HTTP_X_FORWARDED_FOR']; 
    } 
    else { 
        return $_SERVER['REMOTE_ADDR']; 
    } 
} 
  
// Store the IP address 
$vis_ip = getVisIPAddr(); 
  
// Display the IP address 


$ip = $vis_ip;
?>

Then we need to use json plugin to find country name using IP adress which we have find above.

Use Below code to find country name

<php?

// Use JSON encoded string and converts 
// it into a PHP variable 
$ipdat = @json_decode(file_get_contents( 
    "http://www.geoplugin.net/json.gp?ip=" . $ip)); 
   
$name=  $ipdat->geoplugin_countryName;


?>

here $name variable is used to store the name of visitor country.

Whole source code is below.

<?php
function getVisIpAddr() { 
      
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) { 
        return $_SERVER['HTTP_CLIENT_IP']; 
    } 
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
        return $_SERVER['HTTP_X_FORWARDED_FOR']; 
    } 
    else { 
        return $_SERVER['REMOTE_ADDR']; 
    } 
} 
  
// Store the IP address 
$vis_ip = getVisIPAddr(); 
  
// Display the IP address 


$ip = $vis_ip;


// Use JSON encoded string and converts 
// it into a PHP variable 
$ipdat = @json_decode(file_get_contents( 
    "http://www.geoplugin.net/json.gp?ip=" . $ip)); 
   
$name=  $ipdat->geoplugin_countryName;
 echo $name;

?>

This program will print the country of the visitor. Like The country from where you are visiting is

United States

Thank you. Leave comment below if you got an error.

Leave a Reply

Your email address will not be published. Required fields are marked *