Home >Backend Development >PHP Tutorial >PHP implements IP black and white list filtering
The request came from an operation and maintenance colleague. It was necessary to perform IP filtering on a php file. It was inconvenient to configure the server directly, so it was necessary to filter the IP directly at the beginning of the php file.
IP filtering rules can have the following forms:
1. Complete IP address such as: 192.168.0.1
2. A certain IP segment such as: 192.168.0.*.
Operation and maintenance can customize the IP black and white list, which consists of multiple IP filtering rules and is stored in an array. By writing code, the IP black and white list function is implemented. A relatively simple requirement.
First implement a function, the function is to determine whether the IP complies with an IP filtering rule:
function ip_test($ip,$iprule){ $ipruleregexp=str_replace('.*','ph',$iprule); $ipruleregexp=preg_quote($ipruleregexp,'/'); $ipruleregexp=str_replace('ph','\.[0-9]{1,3}',$ipruleregexp); if(preg_match('/^'.$ipruleregexp.'$/',$ip)) return true; else return false; }
After implementing the core function ip_test, the following process is much simpler. It is nothing more than simply traversing each rule in the list and judging Whether the currently connected IP complies with the rules and perform the corresponding steps. P p List, continue to perform operations when IP meets at least one rule.
$curr_ip=$_SERVER['REMOTE_ADDR']; $white_list=array(...); //白名单规则 $test_success=false; foreach($white_list as $iprule){ if(ip_test($curr_ip,$iprule)){ $test_success=true; break; } } if(!$test_success) exit('IP not in white list');E