Get Country of IP Address with PHP

216,836

Solution 1

There are free, easy APIs you can use, like those:

Which one looks the most trustworthy is up to you :)

Otherwise, there are scripts which are based on local databases on your server. The database data needs to be updated regularly, though. Check out this one:

HTH!

Edit: And of course, depending on your project you might want to look at HTML5 Location features. You can't use them yet on the Internet Explorer (IE9 will support it, long way to go yet), but in case your audience is mainly on mobile devices or using Safari/Firefox it's definitely worth to look at it!

Once you have the coordinates, you can reverse geocode them to a country code. Again there are APIs like this one:

Update, April 2013
Today I would recommend using Geocoder, a PHP library which makes it very easy to geocode ip addresses as well as postal address data.

***Update, September 2016
Since Google's privacy politics has changed, you can't use HTML5 Geolocation API if your server doesn't have HTPPS certificate or user doesn't allow you check his location. So now you can use user's IP and check in in PHP or get HTTPS certificate.

Solution 2

There are various web APIs that will do this for you. Here's an example using my service, http://ipinfo.io:

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
echo $details->country; // -> "US"

Web APIs are a nice quick and easy solution, but if you need to do a lot of lookups then having an IP -> country database on your own machine is a better solution. MaxMind offer a free database that you can use with various PHP libraries, including GeoIP.

Solution 3

You can download ip-tables from MaxMind:

http://www.maxmind.com/app/geolite

Import the CSV to your database (make sure to create an index for ip_long_from + ip_long_to). Then you can simply do:

$iplong = ip2long($_SERVER['REMOTE_ADDR']);

// should use mysqli with prepared statements etc, but just an example
mysql_query("
    SELECT country
    FROM ip_table
    WHERE $iplong BETWEEN ip_long_from AND ip_long_to
    LIMIT 1
");

Solution 4

Here's an example using http://www.geoplugin.net/json.gp

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip={$ip}"));
echo $details;

Solution 5

You can get country from IP address with this location API

Code

    echo file_get_contents('https://ipapi.co/8.8.8.8/country/');

Response

   US 

Here's a fiddle. Response is text when you query a specific field e.g. country here. No decoding needed, just plug it into your code.

P.S. If you want all the fields e.g. https://ipapi.co/8.8.8.8/json/, the response is JSON.

Share:
216,836
Tristan
Author by

Tristan

Software Engineer with a Video Game Background

Updated on July 08, 2022

Comments

  • Tristan
    Tristan almost 2 years

    Ideally I'm trying to put together a PHP script that I can query from any web browser and it returns the country of the IP address that accessed the PHP script.

    Is this possible or is there a better solution?

  • Pekka
    Pekka over 13 years
    They are not really built-in. php.net/manual/en/geoip.requirements.php
  • Devator
    Devator almost 12 years
    This, it's an excellent way to get the country from an IP address.
  • Tiago
    Tiago about 10 years
    I would refrain from implementing ipinfo.io in a production environment. I just pinned down major lag in our scripts, to a function that calls ipinfo.io for IP details. Make sure to test your provider choice thoroughly :)
  • Ben Dowling
    Ben Dowling almost 10 years
    That may have been true in the past, but they're now hosted across several providers and several cities for maximum availability and responsiveness - twitter.com/ipinfoio/status/458100167439159296
  • Webby
    Webby over 9 years
    Well I can explain first, because it was my first or second post and number of words was not sufficient so one of moderator gave this post one negative point but I have no idea for second.
  • user151496
    user151496 about 9 years
    i don't understand how do people get the localized city/country names, as geolite offers only a couple of languages
  • Mikhail Bunkin
    Mikhail Bunkin over 8 years
    The most amazing thing is that adding indexes for "from" and "to" columns made the query take 10 times longer. Keeping the database unindexed worked best for me, together with LIMIT 1. Perhaps because the data is sorted in the CSV. Go figure.
  • Felipe Francisco
    Felipe Francisco almost 8 years
    I think something changed on this api since the answer was posted, I'm now receiving the following error: "The GoogleMaps provider does not support IP addresses, only street addresses."
  • Cedric Ipkiss
    Cedric Ipkiss over 7 years
    Correct it, then.
  • Nikola Obreshkov
    Nikola Obreshkov almost 6 years
    I used ipapi.co for a couple of months but they have stopped processing my IP (HTTP/1.1 429 Too Many Requests) after something like 300-400 queries (4-5 per day). The information on their website 1000 queries per day are free is NOT true! I don't recommend them if you are looking for a free service.
  • German Khokhlov
    German Khokhlov over 5 years
    It doesn't work correctly. "193.238.152.59" recognized as FR, but it's UA.
  • Laurent
    Laurent almost 5 years
    ipregistry.co is twice faster and accurate than ipdata.co: ipregistry.co/status (disclaimer: I run the service)
  • Laurent
    Laurent almost 5 years
    I suggest trying out Ipregistry (disclaimer: I run the service).
  • user6250071
    user6250071 almost 2 years
    @NikolaObreshkov We are sorry to hear about your experience. Since we don't require a sign-up, our free tier receives heavy traffic from certain regions and some users can get rate limited early. We are always happy to resolve it If you contact us with this issue.