Skip to content

Instantly share code, notes, and snippets.

@markbrody
Last active February 23, 2018 22:16
Show Gist options
  • Save markbrody/2fde3818a9b7b4277d04 to your computer and use it in GitHub Desktop.
Save markbrody/2fde3818a9b7b4277d04 to your computer and use it in GitHub Desktop.
php whitelist that supports cidr notation
<?php
function is_whitelisted($remote_ip) {
$whitelisted = false;
$remote_ip = sprintf("%u", ip2long($remote_ip));
$records = ["127.0.0.0/10", "10.0.0.1", "192.168.1.0/24"];
foreach ($records as $record) {
$ip = $record;
$cidr = 32;
if (strpos($record, "/"))
list($ip, $cidr) = explode("/", $record);
$start = sprintf("%u", ip2long($ip));
$num_hosts = pow(2, 32 - $cidr) - 1;
if ($remote_ip >= $start && $remote_ip <= $start + $num_hosts) {
$whitelisted = true;
break;
}
}
return $whitelisted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment