For a website I'm developing, I want it to like say how many users from each country have visited my site, but what I'm curious is how to get the user's country (From their IP, Maybe?)? I've looked around for APIs for hours upon hours but I couldn't find anything decent. Does anyone have any recommendations? Thanks for the help :).
You can use external API's like geoplugin.net
$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=76.109.14.196");
echo $xml->geoplugin_countryName ;
Output Country
United States
Full XML Response
<geoPlugin>
<geoplugin_request>76.109.14.196</geoplugin_request>
<geoplugin_status>200</geoplugin_status>
<geoplugin_city>West Palm Beach</geoplugin_city>
<geoplugin_region>FL</geoplugin_region>
<geoplugin_areaCode>561</geoplugin_areaCode>
<geoplugin_dmaCode>548</geoplugin_dmaCode>
<geoplugin_countryCode>US</geoplugin_countryCode>
<geoplugin_countryName>United States</geoplugin_countryName>
<geoplugin_continentCode>NA</geoplugin_continentCode>
<geoplugin_latitude>26.761600494385</geoplugin_latitude>
<geoplugin_longitude>-80.091598510742</geoplugin_longitude>
<geoplugin_regionCode>FL</geoplugin_regionCode>
<geoplugin_regionName>Florida</geoplugin_regionName>
<geoplugin_currencyCode>USD</geoplugin_currencyCode>
<geoplugin_currencySymbol>$</geoplugin_currencySymbol>
<geoplugin_currencyConverter>1</geoplugin_currencyConverter>
</geoPlugin>
Simple Function to Get IP
function getIP() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
The basic approach is to record the incoming IP address (it's in $_SERVER['REMOTE_ADDR']
) and then use a geolocation database to convert that into country information.
You will need to keep your geolocation database up-to-date, remember.
There are several places which offer geolocation databases. Some cost (they tend to be more accurate and more up-to-date) but the free ones are usually pretty good, too.
Sometimes we need to manage the content or currency based on the visitor's country. Usually this situation arises to every developer, they try to find a better solution. You can find the article here in detail - http://virallangaliya.blogspot.in/2013/04/how-to-find-city-and-country-of-visitor.html
© 2022 - 2024 — McMap. All rights reserved.