Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get user country name from user ip address in php

Tags:

php

how to get country name from user IP address

I have IP addresses of user i get the country name of user base on user IP address how it is possible in php ?

function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}
like image 458
Ghulam Abbas Avatar asked May 09 '16 09:05

Ghulam Abbas


2 Answers

Try this

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

$IPaddress  =  'Your ip address of user';

$details    =   ip_details("$IPaddress");

//echo $details->city;   
 echo $details->country;  
//echo $details->org;      
//echo $details->hostname; 
like image 58
Web Artisan Avatar answered Oct 25 '22 15:10

Web Artisan


For getting IP address you can use the function given by you or simply you can use

$_SERVER['REMOTE_ADDR']

to get the IP address of the user use as follow:

$ip =  $_SERVER['REMOTE_ADDR'];   // ip = 8.8.8.8
$country = file_get_contents('http://ipinfo.io/8.8.8.8/country'); // for more info visit [enter link description here][1] 
echo $country;  // output = US | UK | IN as per ip (just one country code)
like image 28
Sunil Kumar Avatar answered Oct 25 '22 16:10

Sunil Kumar