Tp5 获取IPV6地址

修改Request类ip()方法

public function ip($type = 0, $adv = true)
    {
        $type      = $type ? 1 : 0;
        static $ip = null;
        if (null !== $ip) {
            return $ip[$type];
        }

        $httpAgentIp = Config::get('http_agent_ip');

        if ($httpAgentIp && isset($_SERVER[$httpAgentIp])) {
            $ip = $_SERVER[$httpAgentIp];
        } elseif ($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'];
        }
        $check_res = $this->isValidIP($ip);
        if(!$check_res){
            $ip = ltrim(rtrim($ip,"]"),"[");
        }
        // IPv4地址
        if (filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4)) {
//            echo "这是一个有效的IPv4地址
"; // IP地址合法验证 $long = sprintf("%u", ip2long($ip)); $ip = $long ? [$ip, $long] : ['0.0.0.0', 0]; return $ip[$type]; } else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { // echo "这是一个有效的IPv6地址
"; return $ip; } else { // echo "无法识别该IP地址的类型
"; $long = sprintf("%u", ip2long($ip)); $ip = $long ? [$ip, $long] : ['0.0.0.0', 0]; return $ip[$type]; } }
/**
     * 检测是否是合法的IP地址
     *
     * @param string $ip   IP地址
     * @param string $type IP地址类型 (ipv4, ipv6)
     *
     * @return boolean
     */
    public function isValidIP( $ip,  $type = '')
    {
        switch (strtolower($type)) {
            case 'ipv4':
                $flag = FILTER_FLAG_IPV4;
                break;
            case 'ipv6':
                $flag = FILTER_FLAG_IPV6;
                break;
            default:
                $flag = 0;
                break;
        }

        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
    }

你可能感兴趣的:(ThinkPHP,5,php,thinkphp)