php | whitelist

PHP IP Address Whitelist with Wildcards:


Function to check if ip is in the whitelist:
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;}
    else{
        foreach($whitelist as $i){
            $wildcardPos = strpos($i, "*");
            if($wildcardPos !== false && substr($_SERVER['REMOTE_ADDR'], 0, $wildcardPos) . "*" == $i){return true;}
        }
    }

    return false;
}

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

Reference:

stackoverflow