-
-
Save ipcpu/15c9b10aa42c94756fc0de9c4d591a8f to your computer and use it in GitHub Desktop.
php whitelist that supports cidr notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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