Saturday, June 13, 2026
HomeLanguagesHow to get visitors country from their IP in PHP ?

How to get visitors country from their IP in PHP ?

Overview: To obtain the details like country, continent, city, etc of the visitor, first we need to get the IP of the visitor. The IP address can be obtained with the help of superglobal $_SERVER in PHP. Finally, with the use of API geoPlugin, we can obtain information about the IP address i.e. visitor of the website.

Step 1: Getting the visitor’s IP address.
$_SERVER is a PHP Superglobals variable which holds information about headers, IP, script details, etc. Elements like REMOTE_ADDR, HTTP_X_REAL_IP, HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR can be used to get the IP from this super global.

Example: This example obtain the IP of the visitors.




<?php
// 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'];
    }
}
  
// Store the IP address
$vis_ip = getVisIPAddr();
  
// Display the IP address
echo $vis_ip;
   
?>


Note: In case of CloudFlare, one may need to use elements like HTTP_X_REAL_IP to obtain the IP address.

Step 2: Use API to get the details of the visitor’s IP: Here, we are going to use the geoPlugin API to get the details of the visitor. The api will deliver a json object, which can convert to a PHP variable.




<?php
// PHP code to obtain country, city, 
// continent, etc using IP Address
  
$ip = '52.25.109.230';
  
// 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));
   
echo 'Country Name: ' . $ipdat->geoplugin_countryName . "\n";
echo 'City Name: ' . $ipdat->geoplugin_city . "\n";
echo 'Continent Name: ' . $ipdat->geoplugin_continentName . "\n";
echo 'Latitude: ' . $ipdat->geoplugin_latitude . "\n";
echo 'Longitude: ' . $ipdat->geoplugin_longitude . "\n";
echo 'Currency Symbol: ' . $ipdat->geoplugin_currencySymbol . "\n";
echo 'Currency Code: ' . $ipdat->geoplugin_currencyCode . "\n";
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
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS