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?
The geoip_country_code_by_name() is an inbuilt function in PHP which helps to generate the two-letter country code (Each country is assigned a two-letter country code. For Example: US for United States). The function takes the hostname or IP Address as an argument and generates the two letter country code.
From PHP.net: The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP. This is just a php module for the MaxMind database, which is payware.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With