Skip to content

Instantly share code, notes, and snippets.

@magenx
Created July 10, 2014 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magenx/31522a152bd93650022b to your computer and use it in GitHub Desktop.
Save magenx/31522a152bd93650022b to your computer and use it in GitHub Desktop.
CIDR -> IP -> MATCH
$cidrs = array(
'192.168.1.20/27',
'192.168.0.10/32'
);
function cidr_match($ip, $range)
{
list ($subnet, $bits) = explode('/', $range);
$ip = ip2long($ip);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask;
return ($ip & $mask) == $subnet;
}
$user_ip = $_SERVER['REMOTE_ADDR'];
$validaddr = false;
foreach ($cidrs as $addr)
if (cidr_match($user_ip, $addr)) {
$validaddr = true;
break;
}
if ($validaddr) {
echo "CORRECT IP ADDRESS";
}
else {
echo "INCORRECT IP ADDRESS";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment