Skip to content

Instantly share code, notes, and snippets.

@ipcpu
Forked from markbrody/cidr_whitelist.php
Last active January 10, 2017 08:18
Show Gist options
  • Save ipcpu/15c9b10aa42c94756fc0de9c4d591a8f to your computer and use it in GitHub Desktop.
Save ipcpu/15c9b10aa42c94756fc0de9c4d591a8f to your computer and use it in GitHub Desktop.
php whitelist that supports cidr notation
<?php
////判断IP是不是在白名单内的算法-PHP
////$_SERVER['REMOTE_ADDR'] = $_SERVER['argv'][1];
$ip="10.1.1.1";
$client = sprintf('%u', ip2long($ip));
$whitelist = array('127.0.0.0/10', '10.0.0.0/8', '192.168.1.0/24','60.207.94.32/27');
$whitelisted = false;
foreach ($whitelist as $range) {
$ip = $range;
$cidr = 32;
if (strpos($range, '/'))
list($ip, $cidr) = explode('/', $range);
$start = sprintf('%u', ip2long($ip));
$hosts = pow(2, 32 - $cidr) -1;
$end = $start + $hosts;
if ($client >= $start && $client <= $end) {
$whitelisted = true;
break;
}
}
echo ($whitelisted ? 'is' : "isn't") . " allowed\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment