This functions takes an IP-mask and an IP and returns true if the IP matches the given mask. A mask can be of the form 192.168.0.0/16 or 192.168.0.0/255.255.0.0 or even with long numbers.
function ipmatch($mask, $ip) { list($mip, $mmask) = explode('/', $mask, 2); if (strpos($ip, '.') !== false) $ip = ip2long($ip); $ip = decbin($ip); if (strpos($mip, '.') !== false) $mip = ip2long($mip); $mip = decbin($mip); if (strpos($mmask, '.') !== false) $mmask = decbin(ip2long($mmask)); // convert subnet to mask elseif ($mmask <= 32) $mmask = str_repeat('1', $mmask) . str_repeat('0', (32-$mmask)); // convert numeric mask to binary number else $mmask = decbin($mmask); // PHP doesn't like this large numbers, so had to convert to binary (0/1-string) $matches = true; for ($i=0;$i<32;$i++) { if ($mmask{$i} == '1' && ($ip{$i} != $mip{$i})) { $matches = false; break; } } return $matches; }