JGeer
JGeer

Reputation: 1852

Check IP country and display full country name

I use the following code to check the location of the users IP. But this displays the country like 'US' and 'UK'.

How can I solve this to display the full country name? Like 'United States' and 'United Kingdom'?

CODE:

<?php

$ipaddress = $_SERVER['REMOTE_ADDR'];

function ip_details($ip) {
  $json = file_get_contents("http://ipinfo.io/{$ip}/json");
  $details = json_decode($json, true);
  return $details;
}

$details = ip_details($ipaddress);
echo $details['country'];

?>

Upvotes: 1

Views: 1915

Answers (2)

Chuyenim
Chuyenim

Reputation: 3

I think you can use checkgeoip.com. It's free:

<?php
// set IP address and API key 
$ip = '72.229.28.185';
$api_key = 'YOUR_API_KEY';

// Initialize CURL:
$ch = curl_init('https://api.checkgeoip.com/'.$ip.'?api_key='.$api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the data:
$json = curl_exec($ch);
curl_close($ch);

// Decode JSON response:
$api_result = json_decode($json, true);

// Output the "city" object
echo $api_result['city'];
?>

Upvotes: 0

weigreen
weigreen

Reputation: 1242

It look like you are using ipinfo's API.

They only provide you short country name.

However, ipinfo's document said you can use "country.io"'s data to achieve your need.

Just convert it into php array, and you can transfer US to United States

<?php

$ipaddress = $_SERVER['REMOTE_ADDR'];

$code = ["US" => "United States", "GB" => "United Kingdom"];

function ip_details($ip) {
    $json = file_get_contents("http://ipinfo.io/{$ip}/json");
    $details = json_decode($json, true);
    return $details;
}

$details = ip_details($ipaddress);
if(array_key_exists($details['country'], $code)){
    $details['country'] = $code[$details['country']];
}
echo $details['country'];

?>

Upvotes: 2

Related Questions