Many different ways to do it...
One third party service you could use is http://ipinfodb.com. They provide hostname, geolocation and additional information.
Register for an API key here: http://ipinfodb.com/register.php. This will allow you to retrieve results from their server, without this it will not work.
Copy and past the following PHP code:
$ipaddress = $_SERVER['REMOTE_ADDR'];
$api_key = 'YOUR_API_KEY_HERE';
$data = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=$api_key&ip=$ipaddress&format=json");
$data = json_decode($data);
$country = $data['Country'];
Downside:
Quoting from their website:
Our free API is using IP2Location Lite version which provides lower accuracy.
This function will return country name using the http://www.netip.de/ service.
$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
$response=@file_get_contents('http://www.netip.de/search?query='.$ip);
$patterns=array();
$patterns["country"] = '#Country: (.*?) #i';
$ipInfo=array();
foreach ($patterns as $key => $pattern)
{
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
return $ipInfo;
}
print_r(geoCheckIP($ipaddress));
Output:
Array ( [country] => DE - Germany ) // Full Country Name