How to Detect Country/Location of Visitor

How to detect country / location of visitor?

NetImpact provide a free API for geolocation lookup by IP, ProgrammableWeb also has a roundup of GeoIP lookup providers. This involves a small amount of latency while your application completes an API call (unless your application can use a non-blocking call) but is the least intrusive manner of detecting a visitor's country of origin.

How to get visitor's location (i.e. country) using geolocation?

You don't need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.

Here is a client-side example with Ipregistry (disclaimer, I am working for):

fetch('https://api.ipregistry.co/?key=tryout')
.then(function (response) {
return response.json();
})
.then(function (payload) {
console.log(payload.location.country.name + ', ' + payload.location.city);
});

If you really need to get their location, you can get their lat/lng with that method, then query Google's or Yahoo's reverse geocoding service.

How to detect visitor country using simple Javascript

I have added the code for region and city which was missing, try this it works now,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function()
{
const country = geoplugin_countryName();
const countryCode = geoplugin_countryCode();
const city = geoplugin_city();
const region = geoplugin_region();
console.log(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`);
alert(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`)
});
});

How to detect browser country in client site?

There are multiple options to determine the locale. In descending order of usefulness, these are:

  1. Look up the IP address, with an IP geolocation service like Maxmind GeoIP. This is the location the request is coming from, i.e. if an American vacations in Italy and uses a Swedish VPN, it will return Sweden.

It can only be done with the help of the server. The main advantage is that it's very reliable. The accuracy will be country or region for free services, city or region for paid ones.


  1. Look up the precise location on Earth from the browser with the geolocation API. An American vacationing in Italy using a Swedish VPN will register as Italy.

The answer will be very precise, usually no more than 10m off. In principle, it could work client-side, although you may want to perform the coordinate -> country lookup on the server. The main disadvantages are that not all devices have either GPS or WiFi position, and that it generally requires explicit user consent.


  1. Look in the Accept-Language header on the server (or with the help of the server), and extract the locale information. An American vacationing in Italy using a Swedish VPN will register as USA.

The downside is that this is a setting that's extremely easy to change. For instance, English speakers around the world may prefer en-US settings in order to avoid machine-translated text. On modern browsers (as of writing not IE/Edge, and only Safari 11+), you can also request navigator.languages.


  1. navigator.language is the first element of the navigator.languages header. All of the considerations of navigator.languages apply. On top, this information can sometimes be just the language without any locale (i.e. en instead of en-US).

  2. Use another, third-party service. For instance, if the user signs in via a Single-Sign-On system such Facebook connect, you can request the hometown of the user. This information is typically very unreliable, and requires a third party.

How to identify each visitors country/location using php?

PHP has no built-in method to determine the location of a website visitor.

The best you can do automatically is to look up their IP address in an IP-to-location database.

You can get one for free from MaxMind. They have a PHP API available for using the database.

Getting visitors country from their IP

Try this simple PHP function.

<?php

function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
$purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
$support = array("country", "countrycode", "state", "region", "city", "location", "address");
$continents = array(
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
);
if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
switch ($purpose) {
case "location":
$output = array(
"city" => @$ipdat->geoplugin_city,
"state" => @$ipdat->geoplugin_regionName,
"country" => @$ipdat->geoplugin_countryName,
"country_code" => @$ipdat->geoplugin_countryCode,
"continent" => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
"continent_code" => @$ipdat->geoplugin_continentCode
);
break;
case "address":
$address = array($ipdat->geoplugin_countryName);
if (@strlen($ipdat->geoplugin_regionName) >= 1)
$address[] = $ipdat->geoplugin_regionName;
if (@strlen($ipdat->geoplugin_city) >= 1)
$address[] = $ipdat->geoplugin_city;
$output = implode(", ", array_reverse($address));
break;
case "city":
$output = @$ipdat->geoplugin_city;
break;
case "state":
$output = @$ipdat->geoplugin_regionName;
break;
case "region":
$output = @$ipdat->geoplugin_regionName;
break;
case "country":
$output = @$ipdat->geoplugin_countryName;
break;
case "countrycode":
$output = @$ipdat->geoplugin_countryCode;
break;
}
}
}
return $output;
}

?>

How to use:

Example1: Get visitor IP address details

<?php

echo ip_info("Visitor", "Country"); // India
echo ip_info("Visitor", "Country Code"); // IN
echo ip_info("Visitor", "State"); // Andhra Pradesh
echo ip_info("Visitor", "City"); // Proddatur
echo ip_info("Visitor", "Address"); // Proddatur, Andhra Pradesh, India

print_r(ip_info("Visitor", "Location")); // Array ( [city] => Proddatur [state] => Andhra Pradesh [country] => India [country_code] => IN [continent] => Asia [continent_code] => AS )

?>

Example 2: Get details of any IP address. [Support IPV4 & IPV6]

<?php

echo ip_info("173.252.110.27", "Country"); // United States
echo ip_info("173.252.110.27", "Country Code"); // US
echo ip_info("173.252.110.27", "State"); // California
echo ip_info("173.252.110.27", "City"); // Menlo Park
echo ip_info("173.252.110.27", "Address"); // Menlo Park, California, United States

print_r(ip_info("173.252.110.27", "Location")); // Array ( [city] => Menlo Park [state] => California [country] => United States [country_code] => US [continent] => North America [continent_code] => NA )

?>


Related Topics



Leave a reply



Submit