禁止單個IP或ip段訪問
阿新 • • 發佈:2018-01-13
break 使用 return max ++ check explode convert body
//IP禁止判斷接口,返回true則為找到 function checkIp($ip, $ipbanned) { $ipbannedFlag = false; if (!empty($ipbanned)) { foreach ($ipbanned as $data) { if (strpos($data, ‘*‘)) { $ip_min = convert_ip("min", $data); $ip_max= convert_ip("max", $data); $result = ipforbidden($ip, $ip_min, $ip_max); if ($result == 1) { //找到 $ipbannedFlag = true; break; } } else {if ($ip == $data) { //找到 $ipbannedFlag = true; break; } } } } return $ipbannedFlag; } function convert_ip($op, $ip) { $arr_ip = explode(".", $ip);$arr_temp = array(); $i = 0; $result = ‘‘; $ip_val = $op == "max" ? "255" : "1"; foreach ($arr_ip as $key => $val) { $i++; $val = $val == "*" ? $ip_val : $val; $arr_temp[] = $val; } for ($i = 4 - $i; $i > 0; $i--) { $arr_temp[] = $ip_val; } $comma = ""; foreach ($arr_temp as $v) { $result .= $comma . $v; $comma = "."; } return $result; } //判斷IP是否被限並返回 function ipforbidden($ip, $ip_from, $ip_to) { $from = strcmp(ip2long($ip), ip2long($ip_from)); $to = strcmp(ip2long($ip), ip2long($ip_to)); if ($from >= 0 && $to <= 0) { return 1; } else { return 0; } }
//使用方法 $ipbanned = [ ‘61.135.165.*‘, ‘61.135.186.*‘, ‘127.0.0.1‘, ]; $user_ip = ‘127.0.0.1‘; $result = checkIp($user_ip, $ipbanned); if ($result) exit(‘禁止訪問‘);
禁止單個IP或ip段訪問