[ php ] 获取请求 IP 地址,及所处 IP 所在服务商代码

// 获取 IP 地址 
function get_remote_addr()
{
    if (isset($_SERVER["HTTP_X_REAL_IP"]))
    {
        return $_SERVER["HTTP_X_REAL_IP"];
    }
    else if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
    {
        return preg_replace('/^.+,\s*/', '', $_SERVER["HTTP_X_FORWARDED_FOR"]);
    }
    else
    {
        return $_SERVER["REMOTE_ADDR"];
    }
}
// 根据 IP 地址,获取 IP 所处运营商名称
function get_ip_location_cn($ip)
{
    if (function_exists('curl_init'))
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://cn.ip.cn/?ip=" . $ip);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.55.1");
        $result = curl_exec($ch);
        if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
            $result = '';
        }
        curl_close($ch);
    }
    else
    {
        $options = array('http'=>array('method'=>"GET", 'header'=>"User-Agent: curl/7.55.1\r\n"));
        $result = file_get_contents('http://cn.ip.cn/?ip=' . $ip, false, stream_context_create($options));
        if ($result === false) {
            $result = '';
        }
    }
    $location = trim(substr($result, strrpos($result, ':')+3));
    return substr($location, 0, 100);
}

你可能感兴趣的:(php)