php获取用户真实ip地址与地理位置

echo getcposition(getIP());

//获取用户真实ip 
function getIP()
{
    if (isset($_SERVER)) {
        if (isset($_SERVER[HTTP_X_FORWARDED_FOR])) {
            $realip = $_SERVER[HTTP_X_FORWARDED_FOR];
        } elseif (isset($_SERVER[HTTP_CLIENT_IP])) {
            $realip = $_SERVER[HTTP_CLIENT_IP];
        } else {
            $realip = $_SERVER[REMOTE_ADDR];
        }
    } 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");
        }
    }
    return $realip;
}


//获取ip地址的地理位置
function getcposition($ip)
{
//这个api不能频繁调用
    $res1 = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
    $res1 = json_decode($res1, true);

    //print_r($res1);
    if ($res1["code"] == 0) {
        return $res1['data']["country"] . $res1['data']["region"] . $res1['data']["city"] . "_" . $res1['data']["isp"];
    } else {
        return "未知";
    }
}

你可能感兴趣的:(php获取用户真实ip地址与地理位置)