How to get country code and country name from the visitor's IP

<?php
// IP from visitor
if (isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['REMOTE_ADDR']) && filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP)) {
    $ip = $_SERVER['REMOTE_ADDR'];
}
if (!empty($ip)) {
    // get Geolocation from IP (Free API)
    $query = json_decode(file_get_contents('http://ip-api.com/json/'.$ip));
    if ($query) {
        if ($query->status == 'success') {
            // success
            echo $ip.' from '.$query->country.' ('.$query->countryCode.')';
        } else {
            // error
            echo $query->query.' '.$query->message;
        }
        exit;
    }
}
echo 'Unable to get country';

 

Related

^