PHP限制IP访问

/**
 * 获取客户端IP
 */
function getClientIP()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
    {
        $ip = getenv("HTTP_CLIENT_IP");
    }
    elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
    {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    }
    elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
    {
        $ip = getenv("REMOTE_ADDR");
    }
    elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    else
    {
        $ip = "unknown";
    }
    return ($ip);
}

禁止单IP访问

$ip = getClientIP();
$bannedIp = array(
    "127.0.0.1",
    "203.0.0.1",
    "56.12.50.65",
    "192.168.1.88"
);
if (in_array($ip, $bannedIp))
{
    die ("未经授权的访问!");
}

IP段访问限制

$ip = ip2long(getClientIP());
$bannedBegin = ip2long("217.0.0.0");    // ip段上   
$bannedEnd = ip2long("217.255.255.255");    // ip段尾   
if ($ip > $bannedBegin && $ip < $bannedEnd)
{
    print "Banned";
    exit();
}