您好,欢迎访问一九零五行业门户网

php限制IP和IP段的代码(白名单)

实现的原理比较简单只要获取用户ip然后再在我们黑名单库中验证一下当前ip是不是存在即可进行过滤操作了,具体例子如下。
段代码是我在网上搜相关解决方法时搜到的,这个类的makepregip函数逻辑有点问题,我修改了下可以使用了。这个类得功能是允许白名单中的ip地址访问,如果要实现限制黑名单中的ip地址访问,简单修改下checkip函数中的代码逻辑就可以了。
使用方法
 代码如下 复制代码
$allow_ip = array(192.168.1.1,210.10.2.1-20,222.34.4.*,127.0.0.1);
$oblock_ip = new allowip($allow_ip);
if( !$oblock_ip->checkip() ){
  echo '您的ip为:';
  echo $oblock_ip->ip;
  exit('禁止访问');
}
allowip类文件
 代码如下 复制代码
class allowip {
function __construct($allow_ip){
        if (empty($allow_ip)) {
          return false;
        }
        $this->allow_ip = $allow_ip;
        $this->ip = '';
}
private function makepregip($str)
    { 
        if (strstr($str,-)) {
$aip = explode(.,$str);
foreach ($aip as $k=>$v) {
                if (!strstr($v,-)) {
                    $preg_limit .= $this->makepregip($v);
                    $preg_limit .= .;
                } else{
                    $aipnum = explode(-,$v);
                    for($i=$aipnum[0];$i                        $preg .=$preg?|.$i:[.$i;
                    }
                    $preg_limit .=strrpos($preg_limit,.,1)==(strlen($preg_limit)-1)?$preg.]:..$preg.];
                }
            }
        }
        else {
            $preg_limit = $str;
        }
return $preg_limit;
    }
private function getallblockip(){
        if ($this->allow_ip) {
            $i = 1;
            foreach ($this->allow_ip as $k=>$v) {
                $ipaddres = $this->makepregip($v);
$ip = str_ireplace(.,.,$ipaddres);
                $ip = str_replace(*,[0-9]{1,3},$ip);
                $ipaddres = /.$ip./;
                $ip_list[] = $ipaddres;
                $i++;
            }
        }
        return $ip_list;
    }
public function checkip() {
        $iptable = $this->getallblockip();
        $isjoined = false;
        //取得用户ip
        $ip = $this->get_client_ip();
        $ip = trim($ip);
        //在白名单中
        if ($iptable) {
            foreach($iptable as $value) {
                if (preg_match({$value},$ip)) {
                    $isjoined = true;
                    break;
                }
            }
        }
        //不在白名单中
        if( !$isjoined ){
            return false;
        }
        return true; 
    }
private function get_client_ip(){
        if (getenv(http_client_ip) && strcasecmp(getenv(http_client_ip), unknown))
            $ip = getenv(http_client_ip);
        else if (getenv(http_x_forwarded_for) && strcasecmp(getenv(http_x_forwarded_for), unknown))
            $ip = getenv(http_x_forwarded_for);
        else if (getenv(remote_addr) && strcasecmp(getenv(remote_addr), unknown))
            $ip = getenv(remote_addr);
        else if (isset($_server['remote_addr']) && $_server['remote_addr'] && strcasecmp($_server['remote_addr'], unknown))
            $ip = $_server['remote_addr'];
        else
            $ip = unknown;
        $this->ip = $ip;
        return($ip);
   }
}
其它类似信息

推荐信息