PHP中根据IP地址判断所在城市等信息

作者:袖梨 2022-06-24


获得IP地址

在 PHP 中得到当前访问者的IP地址,还是比较简单的:

$ip = $_SERVER['REMOTE_ADDR']

上面IP有时获取不到真实IP地址我们可以如下操作


$ip = 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] => 183.16.191.102
        )
)

 

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();

相关文章

精彩推荐