Get Geographic Information from an IP Address for Free

❥ Sponsor

Say you need to know what country someone visiting your website is from, because you have an internationalized site and display different things based on that country. You could ask the user. You might want to have that functionality anyway to make sure your visitors have control, but surely they will appreciate it just being correct out of the gate, to the best of your ability.

There are no native web technologies that have this information. JavaScript has geolocation, but users would have to approve that, and even then you’d have to use some library to convert the coordinates into a more usable country. Even back-end languages, which have access to the IP address in a way that JavaScript doesn’t, don’t just automatically know the country of origin.


You have to ask some kind of service that knows this. The IP Geolocation API is that service, and it’s free.

You perform a GET against the API. You can do it right in the browser if you want to test it:

But you don’t just get the country. You get a whole pile of information you might need to use. I happen to be sitting in Canada and this is what I get for my IP:

   "continent":"North America",
   "address_format":"{{recipient}}\n{{street}}\n{{city}} {{region_short}} {{postalcode}}\n{{country}}",
   "subregion":"Northern America",

With that information, I could easily decide to redirect to the Canadian version of my website, if I have one, or show prices in CAD, or offer a French translation, or whatever else I can think of.

Say you were in PHP. You could get the IP like…

function getUserIpAddr() {
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  return $ip;

The cURL to get the information:

$url = ""; 
$ch = curl_init();  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_URL, $url); 
$result = curl_exec($ch); 

It comes back as JSON, so:

$json = json_decode($result);

And then $json->{'name'}; will be “Canada” if I’m in Canada.

So I can do like:

if ($json->{'name'} == "Canada") {
  // serve index-ca.php
} else {
  // server index.php