Home > Backend Development > PHP Tutorial > php function to ban ip access

php function to ban ip access

WBOY
Release: 2016-07-25 09:00:26
Original
1406 people have browsed it
We provide you with a function that can prohibit IP access, including a function that trusts IP access. Friends in need can refer to it.

The complete code is as follows.

<?
/**
* 禁止IP访问的函数
* 搜集 程序员之家 bbs.it-home.org
*/
function check_ip($range,$ip='') {
if($ip == '') $ip = getenv("REMOTE_ADDR");
if ($ip == "127.0.0.1") return 1;
$result = 1;
if (ereg("([0-9]+).([0-9]+).([0-9]+).([0-9]+)/([0-9]+)",$range,$regs)) {
   $ipl = ip2long($ip);
   $rangel = ip2long($regs[1] . "." . $regs[2] . "." . $regs[3] . "." . $regs[4]);

   $maskl = 0;

for ($i = 0; $i< 31; $i++) {
if ($i < $regs[5]-1) {
$maskl = $maskl + pow(2,(30-$i));
}
}

if (($maskl & $rangel) == ($maskl & $ipl)) {
   return 1;
} else {
   return 0;
}
} else {

$maskocts = split(".",$range);
   $ipocts = split(".",$ip);
   for ($i=0; $i<4; $i++) {
     if (ereg("[([0-9]+)-([0-9]+)]",$maskocts[$i],$regs)) {
      if ( ($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) {
         $result = 0;
      }
}
else
{
if ($maskocts[$i] <> $ipocts[$i]) {
    $result = 0;
}
}
}
}
return $result;
}

function auth_ip(){
   $result = 0;
   $null_check = 1;

   $path = "ip.cf"; //ip限制配置文件,每行的格式为
/*
xxx.xxx.xxx.xxx 比如 127.0.0.2
xxx.xxx.xxx.[yyy-zzz] 比如 1270.0.0.[2-23]
xxx.xxx.xxx.xxx/nn 比如 127.0.0.0/24
*/
$fg=@fopen($path,"r");

while($line=@fgets($fg,1024)){
$line = trim($line);
$line=ereg_replace("#.*","",$line);
if ($line != ""){
$null_check = 0;
if (check_ip($line)) {
fclose($fg);
return 1;
}
}
}
@fclose($fg);
if ($null_check == 1) return 1;
return $result;
}
?>
Copy after login
Articles you may be interested in: PHP bans IP from accessing website php prohibits access to a single IP address or IP range


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template