How to get visitor country from their IP in PHP?

PHP

Step 1:Obtaining the visitor's IP address. 
$_SERVER - this is a PHP variable Superglobals, which contains information about headers, IP, script details, etc. Such elements, how REMOTE_ADDR, HTTP_X_REAL_IP, HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR can be used to get the IP address from this superglobal.Example:This example gets the IP address of visitors.
// PHP code to extract IP 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' ]; } }  
// Save the IP address $vis_ip = getVisIPAddr();  
// Show IP address echo $vis_ip ;  
?>
Note.In the case of CloudFlare you may need to use elements such as HTTP_X_REAL_IP to obtain an IP address.Step 2. Use the API to get IP details URL visitor.Here we are going to use the API geoPlugin for visitor details. The API will deliver a json object that can be converted to a PHP variable.
// PHP code to get country, city,
// continent, etc. using IP address $ip = '52.25.109.230' ;  
// Use a JSON encoded string and convert
// this to a PHP variable $ipdat = @json_decode ( file_get_contents ( " http: / /www.geoplugin.net/json.gp?ip= " . $ip )); echo ' Country Name: ' . $ipdat -> geoplugin_countryName. "" ; echo 'City Name:' ​​ . $ipdat -> geoplugin_city. "" ; echo 'Continent Name:' ​​ . $ipdat -> geoplugin_continentName. "" ; echo 'Latitude:' . $ipdat -> geoplugin_latitude. "" ; echo 'Longitude:' . $ipdat -> geoplugin_longitude. "" ; echo 'Currency Symbol:' . $ipdat -> geoplugin_currencySymbol. "" ; echo 'Currency Code:' . $ipdat -> geoplugin_currencyCode. "" ; echo 'Timezone:' . $ipdat -> geoplugin_timezone;  
?>
Output:
Country Name: United States City Name: Boardman Continent Name: North America Latitude: 45.8491 Longitude: -119.7143 Currency Symbol: $Currency Code: USD Timezone: America / Los_Angeles 




Get Solution for free from DataCamp guru