带有通配符的 PHP IP 地址白名单


PHP IP Address Whitelist with Wildcards

我正在尝试在我的页面中放置几行,以重定向与特定IP地址不匹配的用户。

在这里:

$whitelist = array('111.111.111.111', '112.112.112.112');
if (!(in_array($_SERVER['REMOTE_ADDR'], $whitelist))) {
  header('Location: http://asdf.com');
}

当知道完整地址时,它可以正常工作,但是我如何使其利用通配符并在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;
}

然后使用该功能

if (! isAllowed($_SERVER['REMOTE_ADDR'])) {
    header('Location: http://asdf.com');
}

最好的方法是使用 CIDR:

<?php
  function ipCIDRCheck ($IP, $CIDR) {
    list ($net, $mask) = split ("/", $CIDR);
    $ip_net = ip2long ($net);
    $ip_mask = ~((1 << (32 - $mask)) - 1);
    $ip_ip = ip2long ($IP);
    $ip_ip_net = $ip_ip & $ip_mask;
    return ($ip_ip_net == $ip_net);
  }
  echo ipCheck ("192.168.1.23", "192.168.1.0/24");
?>

修复和解释梁@Chin回答:

/**
 * 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