Get Country of IP Address with PHP
Solution 1
There are free, easy APIs you can use, like those:
- http://ipinfodb.com/ip_location_api.php
- http://www.ipgeo.com/api/
- http://ip2.cc/
- http://www.geobytes.com/IpLocator.htm
- https://iplocate.io/
- and plenty others.
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:
- Example: http://ws.geonames.org/countryCode?lat=47.03&lng=10.2
- More APIs: http://www.geonames.org/export/ws-overview.html
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;
- See more at: http://channasmcs.blogspot.com/2014/11/get-country-of-ip-address-with-php.html#sthash.7u3WCwQq.dpuf
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
.
Comments
-
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 over 13 yearsThey are not really built-in. php.net/manual/en/geoip.requirements.php
-
Devator almost 12 yearsThis, it's an excellent way to get the country from an IP address.
-
Tiago about 10 yearsI 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 almost 10 yearsThat 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 over 9 yearsWell 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 about 9 yearsi don't understand how do people get the localized city/country names, as geolite offers only a couple of languages
-
Mikhail Bunkin over 8 yearsThe 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 almost 8 yearsI 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 over 7 yearsCorrect it, then.
-
Nikola Obreshkov almost 6 yearsI 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 over 5 yearsIt doesn't work correctly. "193.238.152.59" recognized as FR, but it's UA.
-
Laurent almost 5 yearsipregistry.co is twice faster and accurate than ipdata.co: ipregistry.co/status (disclaimer: I run the service)
-
Laurent almost 5 yearsI suggest trying out Ipregistry (disclaimer: I run the service).
-
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.