首页 > 代码库 > php中禁止单个ip与ip段访问的代码小结

php中禁止单个ip与ip段访问的代码小结

1.禁止单个IP

<?php//IP访问限制if(getenv(‘HTTP_CLIENT_IP‘) && strcasecmp(getenv(‘HTTP_CLIENT_IP‘), ‘unknown‘)) {$userip = getenv(‘HTTP_CLIENT_IP‘);} elseif(getenv(‘HTTP_X_FORWARDED_FOR‘) && strcasecmp(getenv(‘HTTP_X_FORWARDED_FOR‘), ‘unknown‘)) {$userip = getenv(‘HTTP_X_FORWARDED_FOR‘);} elseif(getenv(‘REMOTE_ADDR‘) && strcasecmp(getenv(‘REMOTE_ADDR‘), ‘unknown‘)) {$userip = getenv(‘REMOTE_ADDR‘);} elseif(isset($_SERVER[‘REMOTE_ADDR‘]) && $_SERVER[‘REMOTE_ADDR‘] && strcasecmp($_SERVER[‘REMOTE_ADDR‘], ‘unknown‘)) {$userip = $_SERVER[‘REMOTE_ADDR‘];}$banned_ip = array ("127.0.0.1","203.0.0.1","56.12.50.65","192.168.1.88");if (in_array($userip,$banned_ip)) {die ("Your IP is block to connect !");}echo "小鱼阁测试";?> 

2.禁止IP段

<?php //判断IP访问限制 if(getenv(‘HTTP_CLIENT_IP‘) && strcasecmp(getenv(‘HTTP_CLIENT_IP‘), ‘unknown‘)) { $userip = getenv(‘HTTP_CLIENT_IP‘); } elseif(getenv(‘HTTP_X_FORWARDED_FOR‘) && strcasecmp(getenv(‘HTTP_X_FORWARDED_FOR‘), ‘unknown‘)) { $userip = getenv(‘HTTP_X_FORWARDED_FOR‘); } elseif(getenv(‘REMOTE_ADDR‘) && strcasecmp(getenv(‘REMOTE_ADDR‘), ‘unknown‘)) { $userip = getenv(‘REMOTE_ADDR‘); } elseif(isset($_SERVER[‘REMOTE_ADDR‘]) && $_SERVER[‘REMOTE_ADDR‘] && strcasecmp($_SERVER[‘REMOTE_ADDR‘], ‘unknown‘)) { $userip = $_SERVER[‘REMOTE_ADDR‘]; } $ban_range_low=ip2long("217.0.0.0"); //ip段首 $ban_range_up=ip2long("217.255.255.255");//ip段尾 $ip=ip2long($userip]); if ($ip>$ban_range_low && $ip<$ban_range_up) { print "Banned"; exit(); } ?> 

另外请注意,PHP的ip2long有bug,请慎用

<?php echo ip2long(‘58.99.11.1‘),"<br/>";   //输出是 979569409 echo ip2long(‘58.99.011.1‘),"<br/>";  //输出是 979568897 echo ip2long(‘058.99.11.1‘),"<br/>";  //输出是空 ?> 

在PHP 4.x,PHP 5.x中,有前导零的ip转换的结果都不正确。

解决办法,使用自己的函数:

function myip2long($ip){    $ip_arr = split(‘\.‘,$ip);    $iplong = (16777216 * intval($ip_arr[0])) + (65536 * intval($ip_arr[1])) + (256 * intval($ip_arr[2])) + intval($ip_arr[3]);    return $iplong; }

完毕!