Home  >  Article  >  Backend Development  >  How to implement filtering IP black and white lists in PHP

How to implement filtering IP black and white lists in PHP

WBOY
WBOYOriginal
2016-07-25 09:05:291205browse
  1. function ip_test($ip,$iprule){
  2. $ipruleregexp=str_replace('.*','ph',$iprule);
  3. $ipruleregexp=preg_quote($ipruleregexp,'/');
  4. $ ipruleregexp=str_replace('ph','.[0-9]{1,3}',$ipruleregexp);
  5. if(preg_match('/^'.$ipruleregexp.'$/',$ip)) return true;
  6. else return false;
  7. }
Copy the code

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 to determine the currently connected IP Whether it complies with the rules and take the corresponding steps. Whitelist, proceed when an IP meets at least one rule:

  1. $curr_ip=$_SERVER['REMOTE_ADDR'];
  2. $white_list=array(...); //Whitelist rules
  3. $test_success=false;
  4. foreach($white_list as $iprule){
  5. if(ip_test($curr_ip,$iprule)){
  6. $test_success=true;
  7. break;
  8. }
  9. }
  10. if(!$test_success) exit('IP not in white list');
Copy code

Blacklist, proceed when IP does not meet all rules:

  1. $curr_ip=$_SERVER['REMOTE_ADDR'];
  2. $black_list=array(...); //Blacklist rules
  3. foreach($black_list as $iprule){
  4. if(ip_test($curr_ip ,$iprule)){
  5. exit('IP in black list');
  6. }
  7. }
Copy code

At this point, a simple PHP implementation of IP black and white list filtering is completed. I hope it can be used by everyone. Come help. Articles you may be interested in:

PHP security filtering code (provided by 360 with high security factor) PHP filter post, get sensitive data example code php method to filter illegal and special strings php anti-injection code (filter parameters) Very useful PHP code to prevent SQL injection vulnerability filtering function An example of regular filtering using php to prevent sql injection A piece of php code to filter dangerous html



Statement:
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