PHPJN0005:PHP服务器端获取客户端的IP 省份 城市

1,

// 获取客户端的IP地址
function getClientIP()
{
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
foreach ($arr AS $ip) {
$ip = trim($ip);
if ($ip != 'unknown') {
$realip = $ip;
break;
}
}
if(!isset($realip)){
$realip = "0.0.0.0";
}
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$realip = $_SERVER['HTTP_CLIENT_IP'];
} else {
if (isset($_SERVER['REMOTE_ADDR'])) {
$realip = $_SERVER['REMOTE_ADDR'];
} else {
$realip = '0.0.0.0';
}
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$realip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_IP')) {
$realip = getenv('HTTP_CLIENT_IP');
} else {
$realip = getenv('REMOTE_ADDR');
}
}
preg_match("/[d.]{7,15}/", $realip, $onlineip);
$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
return $realip;
};


// echo getClientIP();


// php获取省份和城市数据类型

// {
//     "address":"CN|u5e7fu4e1c|u6df1u5733|None|CHINANET|0|0",
//     "content":{
//             "address":"u5e7fu4e1cu7701u6df1u5733u5e02",
//             "address_detail":{
//                    "city":"u6df1u5733u5e02",
//                    "city_code":340,
//                    "district":"",
//                    "province":"u5e7fu4e1cu7701",
//                    "street":"",
//                    "street_number":""},
//             "point":{"x":"114.02597366","y":"22.54605355"}
//     },
//     "status":0
// }

//获取所在省份和城市
function getCity()
{
    // 获取当前位置所在城市
    $getIp = getClientIP();
    // echo $getIp;

    $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=2TGbi6zzFm5rjYKqPPomh9GBwcgLW5sS&ip={$getIp}&coor=bd09ll");
    $json = json_decode($content);
    // echo $content;

    // $address = $json->{'content'}->{'address'};// 得到如: 广东省深圳市
    // $data['address'] = $address;
    // $return['province'] = mb_substr($data['address'],0,3,'utf-8');
    // $return['city'] = mb_substr($data['address'],3,3,'utf-8');

    // 获取省份和市区信息
    $return['province'] = $json->{'content'}->{'address_detail'}->{'province'};
    $return['city'] = $json->{'content'}->{'address_detail'}->{'city'};
    // echo $json->{'content'}->{'address_detail'}->{'city'};

    return $return;

};


// 打印省份和市区
echo getCity()['province'], getCity()['city'];
// var_dump(json_decode($json));
琥珀君的博客
原文地址:https://www.cnblogs.com/eliteboy/p/14069972.html