根据ip地址获取ip所属城市 --- 2022-08-22

2022-08-22  本文已影响0人  一位先生_

方案一:

获取ip:

function GetIP() {
    if ($_SERVER["HTTP_X_FORWARDED_FOR"]) $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if ($_SERVER["HTTP_CLIENT_IP"]) $ip = $_SERVER["HTTP_CLIENT_IP"];
    else if ($_SERVER["REMOTE_ADDR"]) $ip = $_SERVER["REMOTE_ADDR"];
    else if (getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknown";
    return $ip;
}
echo GetIP();

将IP转换为城市等信息

淘宝提供了一个IP数据接口: http://ip.taobao.com/service/getIpInfo.php?ip=ip地址

$response = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
$result   = json_decode($response);
print_r($result);

输出结果为:

stdClass Object
(
    [code] => 0
    [data] => stdClass Object
        (
            [country] => 中国
            [country_id] => CN
            [area] => 华南
            [area_id] => 800000
            [region] => 广东省
            [region_id] => 440000
            [city] => 深圳市
            [city_id] => 440300
            [county] => 
            [county_id] => -1
            [isp] => 电信
            [isp_id] => 100017
            [ip] => 188.17.192.103
        )
)

方案二:

/**
 *  调用淘宝API根据IP查询地址
 */
public function ip_address()
{
    $ip = '188.17.192.103';
    $durl = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
    // 初始化
    $curl = curl_init();
    // 设置url路径
    curl_setopt($curl, CURLOPT_URL, $durl);
    // 将 curl_exec()获取的信息以文件流的形式返回,而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ;
    // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
    // 执行
    $data = curl_exec($curl);
    // 关闭连接
    curl_close($curl);
    // 返回数据
    return $data;
}

把$ip替换成你要查找的ip就行了

上一篇 下一篇

猜你喜欢

热点阅读