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

时间:2016-02-22 16:45:06

标签: php

我正在尝试将几行放入我的页面,以重定向不匹配某组IP地址的用户。

这是:

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

当完整地址已知时,它可以正常工作,但是如何使用通配符并处理IP范围?

3 个答案:

答案 0 :(得分:3)

您可以创建一个功能来检查用户的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');
}

答案 1 :(得分:2)

最好的方法是使用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");
?>

答案 2 :(得分:1)

修正并解释@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