繁体   English   中英

如何从php中的用户ip地址获取用户国家名称

[英]how to get user country name from user ip address in php

如何从用户IP地址获取国家名称

我有用户的 IP 地址,我根据用户 IP 地址获取用户的国家/地区名称,这在 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;
}

试试这个

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; 

使用apinotes外部地理定位api

例:

http://apinotes.com/ipaddress/ip.php?ip=27.62.184.235

URL:  http://apinotes.com/ipaddress/ip.php
Parameter Name: ip
Value:  27.62.184.23 (ipv4 address)

输出: -

这里我们以Json查询格式显示IP地址详细信息。

{ 
   "status":"success",
   "ip":"27.62.184.23",
   "country_name":"India",
   "country_code":"IN",
   "country_code3":"IND",
   "region_code":"16",
   "region_name":"Maharashtra",
   "city_name":"Mumbai",
   "latitude":18.975,
   "longitude":72.8258
}

要获取 IP 地址,您可以使用您提供的功能,也可以简单地使用

$_SERVER['REMOTE_ADDR']

获取用户的 IP 地址使用如下:

$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)

你可以这样做,其中包括货币:

<?
function resolveIP($ip) {
  $string = file_get_contents("https://ipsidekick.com/{$ip}");
  $json = json_decode($string);
  return $json;
}

$ip = '17.142.160.59';
$json = resolveIP($ip);

echo "Country name: {$json->country->name}\n";
echo "Currency name: {$json->currency->name}\n";
echo "Public holiday: {$json->currency->holiday}\n";
?>

获取当前国家名称和国家经纬度值:

$IPaddress = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$details = $this->ip_details("$IPaddress");
$country_name = $details->country_name;

$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$country_name&sensor=false");
$output_deals = json_decode($geocode_stats);
$latLng = $output_deals->results[0]->geometry->location;
echo $lat = $latLng->lat;
echo $lng = $latLng->lng;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM