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

2018-03-21 20:01 By "Powerless" 2744 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

  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00