Change language

How to get visitor country from their IP in 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 

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method