Get Country of IP Address with PHP [duplicate] Get Country of IP Address with PHP [duplicate] php php

Get Country of IP Address with PHP [duplicate]


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.


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.


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 examplemysql_query("    SELECT country    FROM ip_table    WHERE $iplong BETWEEN ip_long_from AND ip_long_to    LIMIT 1");