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

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

  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57