php实现ip白名单黑名单功能_php技巧

PHP中文网
Release: 2016-05-16 20:21:18
Original
1262 people have browsed it

这个是一个检测ip是否非法的php函数,适应于白名单,黑名单功能开发,主要场景应用于:api来源限制,访问限制等.

代码如下:

/**
 * 安全IP检测,支持IP段检测
 * @param string $ip 要检测的IP
 * @param string|array $ips  白名单IP或者黑名单IP
 * @return boolean true 在白名单或者黑名单中,否则不在
 */
function is_safe_ip($ip="",$ips=""){ 
    if(!$ip) $ip = get_client_ip();  //获取客户端IP
    if($ips){
        if(is_string($ips)){ //ip用"," 例如白名单IP:192.168.1.13,123.23.23.44,193.134.*.*
            $ips = explode(",", $ips);
        }
    }else{ //读取后台配置 白名单IP
        $obj = new Setting();
        $ips = explode(",", $obj->getConfig("whiteip"));  
    }
    if(in_array($ip, $ips)){
        return true;
    }
    $ipregexp = implode('|', str_replace( array('*','.'), array('\d+','\.') ,$ips));  
    $rs = preg_match("/^(".$ipregexp.")$/", $ip);  
    if($rs) return true;
    return ;
}
Copy after login

获取ip地址,这里引用thinkphp内置函数


代码如下:

//应网友要求,贴出 get_client_ip() 函数
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取(有可能被伪装) 
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) 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($arr[0]);
        }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 ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
Copy after login

以上就是本文的全部内容了,希望对大家理解php检测IP有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template