PHP实现-获取用户的真实IP

2018-03-21 20:01 By "Powerless" 2740 0 0

/**
 * 获取客户端IP地址
 * @param integer   $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean   $adv 是否进行高级模式获取(有可能被伪装)
 * @return mixed
 */
public function ip($type = 0, $adv = false)
{
    $type      = $type ? 1 : 0;
    static $ip = null;
    if (null !== $ip) {
        return $ip[$type];
    }

    if ($adv) {
        if (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(current($arr));
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[$type];
}

想要知道用户的真实IP不妨用这个方法试试

评 论

View in WeChat

Others Discussion

  • MySQL分组
    Posted on 2019-11-18 14:00
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • 一些常见的基础概念
    Posted on 2018-11-28 19:10
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00