网站首页 laravel框架
Laravel--IP白名单检测类-保留一下
发布时间:2019-10-17 09:43查看次数:8437
文件下载地址:
代码如下:
<?php
namespace App\Http\Controllers\Util;
class CheckIPUtil
{
//白名单数组
// 192.168.0.1
//192.168.0.*
//["192.168.0.*","192.168.1.1"]
private $iparray;
private function checkIp($ip,$rule)
{
$rule_regexp = str_replace('.*', 'a', $rule);//将.*临时替换成别的符号(.和*都是正则中有特殊含义的符号)
$rule_regexp = preg_quote($rule_regexp, '/');//向规则字符串中增加转义,避免字符串中有其他特殊字符影响正则匹配,非必要语句本例可以忽略
$rule_regexp = str_replace('a', '\.\d{1,3}', $rule_regexp);//将临时符号替换成正则表达式
if (preg_match('/^' . $rule_regexp . '$/', $ip)) {
return true;//匹配
} else {
return false;//不匹配
}
}
/**
* @apiName WhiteIp
* @apiDescription 检测白名
* @param $ip
* @return bool
*/
public function WhiteIp($ip){
foreach ($this->iparray as $role){
if ($this->checkIp($ip,$role)){
return true;
}
}
return false;
}
/**
* @param mixed $iparray
* @return CheckIPUtil
*/
public function setIparray($iparray)
{
$this->iparray = $iparray;
return $this;
} //要检测是IP数组
}关键字词:#linux##andro##