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 :).
3 Answers
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;
}

- 94,024
- 28
- 166
- 217
-
Ah! Figured there was something like that! Thanks for your answer, it really helps :) – xlTobylx Oct 19 '12 at 00:44
-
1"HTTP_X_FORWARDED_FOR should never be used as a means to validate the user’s IP" http://www.thespanner.co.uk/2007/12/02/faking-the-unexpected/ – Jorge Fuentes González Dec 08 '14 at 18:25
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.

- 29,935
- 4
- 60
- 73
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

- 1
- 1