Thinkphp 限制IP段 通配符访问后台页面

记录一下限制特定IP段访问后台等页面代码,支持指定IP,通配符,IP段

$list = '198.198.198.1,196.9.76.*,196.9.76.1-196.9.76.255';
if (!$this->in_host( get_client_ip(), $list )) {
    return false;
}

public function in_host($host, $list) {
        $list = ',' . $list . ',';
        $is_in = false;
        // 1.判断最简单的情况
        $is_in = strpos ( $list, ',' . $host . ',' ) === false ? false : true;
        // 2.判断通配符情况
        if (! $is_in && strpos ( $list, '*' ) !== false) {
            $hosts = array ();
            $hosts = explode ( '.', $host );
            // 组装每个 * 通配符的情况
            foreach ( $hosts as $k1 => $v1 ) {
                $host_now = '';
                foreach ( $hosts as $k2 => $v2 ) {
                    $host_now .= ($k2 == $k1 ? '*' : $v2) . '.';
                }
                // 组装好后进行判断
                if (strpos ( $list, ',' . substr ( $host_now, 0, - 1 ) . ',' ) !== false) {
                    $is_in = true;
                    break;
                }
            }
        }
        // 3.判断IP段限制
        if (! $is_in && strpos ( $list, '-' ) !== false) {
            $lists = explode ( ',', trim ( $list, ',' ) );
            $host_long = ip2long ( $host );
            foreach ( $lists as $k => $v ) {
                if (strpos ( $v, '-' ) !== false) {
                    list ( $host1, $host2 ) = explode ( '-', $v );
                    if ($host_long >= ip2long ( $host1 ) && $host_long <= ip2long ( $host2 )) {
                        $is_in = true;
                        break;
                    }
                }
            }
        }
        return $is_in;
    }
0 条评论

赞助
会员