我正在尝试在我的页面中添加几行以重定向与特定 IP 地址集不匹配的用户。
这里是:
$whitelist = array('111.111.111.111', '112.112.112.112');
if (!(in_array($_SERVER['REMOTE_ADDR'], $whitelist))) {
header('Location: http://asdf.com');
}
Run Code Online (Sandbox Code Playgroud)
当知道完整地址时它工作正常,但我如何利用通配符并在 IP 范围内工作?
您可以创建一个功能来检查用户的 ip 是否被允许。
function isAllowed($ip){
$whitelist = array('111.111.111.111', '112.112.112.112', '68.71.44.*');
// If the ip is matched, return true
if(in_array($ip, $whitelist)) {
return true;
}
foreach($whitelist as $i){
$wildcardPos = strpos($i, "*");
// Check if the ip has a wildcard
if($wildcardPos !== false && substr($ip, 0, $wildcardPos) . "*" == $i) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后使用函数
if (! isAllowed($_SERVER['REMOTE_ADDR'])) {
header('Location: http://asdf.com');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7925 次 |
| 最近记录: |