37

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 spoofing are not a concern.

I know there are geotargeting services and lists, but this seems like overkill since I only need to determine (roughly) if the person is in the US or not.

I was thinking about using JavaScript to get the user's timezone, but this appears to only give the offset, so users in Canada, Mexico, and South America would have the same value as people in the US.

Are there any other bits of information available either in JavaScript, or PHP, short of grabbing the IP address and doing a lookup, to determine this?

David Smith
  • 38,044
  • 11
  • 44
  • 61
  • I think an IP-based solution is the only reliable way. Anything else can be affected by the user's settings. IP-based solutions can also be skewed, but it's harder. – FrustratedWithFormsDesigner Jan 28 '10 at 17:03
  • 4
    @FrustratedWithFormsDesigner - Notice he said, "This is for convenience only, so I am not looking for a super-high degree of accuracy, and security or spoofing are not a concern." so the IP-based solution may be overkill for what he needs. He also said, "...short of grabbing the IP address and doing a lookup, to determine this?" – Taylor Leese Jan 28 '10 at 17:06

8 Answers8

51

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • How could your code be modified so that instead of an alert dialog there is URL redirect that takes a US visitor to a .COM address & allows a Canadian visitor passes through normally? (For a .CA version of a website with a sister .COM version site) –  Feb 16 '11 at 12:30
  • switch statement in the onload event, check the "country" returned from the json function then call Server.Transfer or similiar. – Anonymous Type Feb 16 '11 at 12:30
  • Thanks a lot for the code and the link, its working and awesome :) – Mujahid Jun 13 '11 at 09:46
  • 3
    This doesn't support https :( – Brian Leishman Jun 07 '17 at 22:19
  • I usually use https://www.geo-ip.net/locate?query=stackoverflow.com&format=json it supports ssl connections – Gerard Jul 06 '18 at 10:13
8

The best indicator is probably the HTTP Accept-Language header. It will look something like below in the HTTP request:

GET / HTTP/1.1
Accept: */*
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; MDDC; OfficeLiveConnector.1.4; OfficeLivePatch.0.0; .NET CLR 3.0.30729)
Accept-Encoding: gzip, deflate
Host: www.google.com
Connection: Keep-Alive

You should be able to retrieve this in PHP using the following:

<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
?>
Taylor Leese
  • 51,004
  • 28
  • 112
  • 141
  • 5
    What determines Accept-Language? Is it set by the OS, or can the user influence it? If my co-worker sets up his laptop to use Chinese, what would the Accept-Language be? Also, what about en-gb? – FrustratedWithFormsDesigner Jan 28 '10 at 16:54
  • 1
    It's determined by the user's browser settings. – Taylor Leese Jan 28 '10 at 16:58
  • 2
    @FrustratedWithFormsDesigner: The accept language is determined by the browser. It can be manipulated by the user if they choose to. For example, under firefox, go to Preferences > Content > Languages – Mark Jan 28 '10 at 16:59
  • 1
    It is set by the browser, usually initialized from the OS. Thus, while I am in Canada, I can appear to be in the US, UK, or somewhere else by setting the "Language" as it is usually called in browsers like IE and FF. – JB King Jan 28 '10 at 17:00
  • 1
    @all: This suggests that an IP-based solution is far more reliable. – FrustratedWithFormsDesigner Jan 28 '10 at 17:01
  • 1
    It's not a perfect solution. You would be making an educated guess based on the header. If this is not sufficient you'd have to look into IP-based location services. Note, the OP said, "This is for convenience only, so I am not looking for a super-high degree of accuracy, and security or spoofing are not a concern." – Taylor Leese Jan 28 '10 at 17:02
  • 1
    @FrustratedWithFormsDesigner: Absolutely. Still, `en-us` is a pretty good pointer. – Pekka Jan 28 '10 at 17:03
  • 2
    Guys, Taylor in particular, this looks like it might be the solution I need. As I said, I don't care if the user fakes being from somewhere else, as they are certainly welcome to do so. I'm going to give it some time to see if I get any other good options, but thank you! – David Smith Jan 28 '10 at 17:09
  • 1
    @BigDave: I'm curious now: why is it OK for your results to be so approximate? – FrustratedWithFormsDesigner Jan 28 '10 at 17:27
  • 1
    Given how easy it would be to implement CMS answer, im not sure why using the HTTP header is preferred. There are free geolocating libraries so this is definately the way to go. They are quite accurate for western countries. – Anonymous Type Aug 18 '10 at 23:01
5

I would say that geotargetting is the only method that's even remotely reliable. But there are also cases where it doesn't help at all. I keep getting to sites that think I'm in France because my company's backbone is there and all Internet traffic goes through it.

The HTTP Accept Header is not enough to determine the user locale. It only tells you what the user selected as their language, which may have nothing to do with where they are. More on this here.

Farinha
  • 17,636
  • 21
  • 64
  • 80
1

Wipmania.com & PHP

<?php
$site_name = "www.your-site-name.com";

function getUserCountry() {
    $fp = fsockopen("api.wipmania.com", 80, $errno, $errstr, 5);
    if (!$fp) {
        // API is currently down, return as "Unknown" :(
        return "XX";
    } else {
        $out = "GET /".$_SERVER['REMOTE_ADDR']."?".$site_name." HTTP/1.1\r\n";
        $out .= "Host: api.wipmania.com\r\n";
        $out .= "Typ: php\r\n";
        $out .= "Ver: 1.0\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
        while (!feof($fp)) {
            $country = fgets($fp, 3);
        }
        fclose($fp);
        return $country;
    }
}
?>
Slot Gamer
  • 36
  • 2
1

@rostislav

or using cURL:

public function __construct($site_name) {
    // create a new cURL resource
    $ch = curl_init();

    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
    curl_setopt($ch, CURLOPT_URL, "http://api.wipmania.com".$_SERVER['REMOTE_ADDR']."?".$site_name);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // grab URL and pass it to the browser
    $response = curl_exec($ch);
    $info = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    if (($response === false) || ($info !== 200)) {
        throw new Exception('HTTP Error calling Wipmania API - HTTP Status: ' . $info . ' - cURL Erorr: ' . curl_error($ch));
    } elseif (curl_errno($ch) > 0) {
        throw new Exception('HTTP Error calling Wipmania API - cURL Error: ' . curl_error($ch));
    }

    $this->country = $response;

    // close cURL resource, and free up system resources
    curl_close($ch);
}
Nijboer IT
  • 1,178
  • 1
  • 13
  • 18
1

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

sameeuor
  • 664
  • 7
  • 17
1

My solution, easy and small, in this example i test Canada region from language fr-CA or en-CA

if( preg_match( "/^[a-z]{2}\-(ca)/i", $_SERVER[ "HTTP_ACCEPT_LANGUAGE" ] ) ){

   $region = "Canada";

}
Leonardo Ciaccio
  • 2,846
  • 1
  • 15
  • 17
0

Depending on which countries you want to distinguish, time zones can be a very easy way to achieve it - and I assume it's quite reliable as most people will have the clocks on their computers set right. (Though of course there are many countries you can't distinguish using this technique).

Here's a really simple example of how to do it:

http://unmissabletokyo.com/country-detector

Mike
  • 9
  • 1