How to get the page visitors Country with PHP? [closed]

大兔子大兔子 提交于 2019-12-01 12:56:31

问题


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 :).


回答1:


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>&#36;</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;
}



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/12965801/how-to-get-the-page-visitors-country-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!