php ip地址白名单,php - 带有通配符的PHP IP地址白名单 - 堆栈内存溢出

解决和解释@Chin Leung的答案:

/**

* Returns if the given ip is on the given whitelist.

*

* @param string $ip The ip to check.

* @param array $whitelist The ip whitelist. An array of strings.

*

* @return bool

*/

function isAllowedIp($ip, array $whitelist)

{

$ip = (string)$ip;

if (in_array($ip, $whitelist, true)) {

// the given ip is found directly on the whitelist --allowed

return true;

}

// go through all whitelisted ips

foreach ($whitelist as $whitelistedIp) {

$whitelistedIp = (string)$whitelistedIp;

// find the wild card * in whitelisted ip (f.e. find position in "127.0.*" or "127*")

$wildcardPosition = strpos($whitelistedIp, "*");

if ($wildcardPosition === false) {

// no wild card in whitelisted ip --continue searching

continue;

}

// cut ip at the position where we got the wild card on the whitelisted ip

// and add the wold card to get the same pattern

if (substr($ip, 0, $wildcardPosition) . "*" === $whitelistedIp) {

// f.e. we got

// ip "127.0.0.1"

// whitelisted ip "127.0.*"

// then we compared "127.0.*" with "127.0.*"

// return success

return true;

}

}

// return false on default

return false;

}

测试

$whitelist = [

'111.111.111.111',

'112.112.112.112',

'68.71.44.*',

// '*' would allow any ip btw

];

var_dump(isAllowedIp('68.71.44.11', $whitelist)); // true

var_dump(isAllowedIp('68.71.44.12', $whitelist)); // true

var_dump(isAllowedIp('68.71.14.12', $whitelist)); // false

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值