php 获取IP地址所在地区

<?php
header("Content-Type:text/html; charset=utf-8");

function get_client_ipaddress($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if ($_SERVER['HTTP_X_REAL_IP']) { //nginx 代理模式下,获取客户端真实IP
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { //客户端的ip
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { //浏览当前页面的用户计算机的网关
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
            unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR']; //浏览当前页面的用户计算机的ip地址
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array(
        $ip,
        $long
    ) : array(
        '0.0.0.0',
        0
    );
    return $ip[$type];
}

function findCityByIp($ip){
  $data = iconv("gb2312", "utf-8//IGNORE",file_get_contents('https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=' . $ip . '&ie=utf8&resource_id=6006'));
  $ip_source = json_decode($data,true);
  return $ip_source['data'][0]['location'];
}

$ip_addr =  get_client_ipaddress();
$ip_from =  findCityByIp($ip_addr);

echo $ip_addr . "
";
echo $ip_from;

?>

测试URL

点赞
  1. JackWu说道:
    Google Chrome Windows 10
    太棒了

发表回复

电子邮件地址不会被公开。必填项已用 * 标注