How do you detect a website visitor's country (Specifically, US or not)?

前端 未结 8 2019
無奈伤痛
無奈伤痛 2020-12-12 19:11

I need to show different links for US and non-US visitors to my site. This is for convenience only, so I am not looking for a super-high degree of accuracy, and security or

相关标签:
8条回答
  • 2020-12-12 20:16

    Simply we can use Hostip API

    <?php $country_code = file_get_contents("http://api.hostip.info/country.php"); <br/>if($country_code == "US"){ echo "You Are USA"; } <br/>else{ echo "You Are Not USA";} ?>
    

    All Country codes are here.. http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

    0 讨论(0)
  • 2020-12-12 20:17

    There are some free services out there that let you make country and ip-based geolocalization from the client-side.

    I've used the wipmania free JSONP service, it's really simple to use:

    <script type="text/javascript">
      // plain JavaScript example
      function jsonpCallback(data) { 
        alert('Latitude: ' + data.latitude + 
              '\nLongitude: ' + data.longitude + 
              '\nCountry: ' + data.address.country); 
      }
    </script>
    <script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"
            type="text/javascript"></script>
    

    Or if you use a framework that supports JSONP, like jQuery you can:

    // jQuery example
    $.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) { 
      alert('Latitude: ' + data.latitude + 
            '\nLongitude: ' + data.longitude + 
            '\nCountry: ' + data.address.country); 
    });
    

    Check the above snippet running here.

    0 讨论(0)
提交回复
热议问题