Home > Backend Development > PHP Tutorial > PHP implements IP black and white list filtering

PHP implements IP black and white list filtering

巴扎黑
Release: 2016-11-23 10:56:00
Original
1653 people have browsed it

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;
   
}
Copy after login

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');
Copy after login
E
blacklist, when IP does not meet all rules, continues to perform operations. . This blog is mainly for those whose main business is not development, such as technical support, operation and maintenance, etc. Because it was too simple, I didn’t want to write it at first. Later, the colleague thanked me for my help and told me that he had been looking for this on the Internet for a long time but could not find a suitable solution. I thought that maybe someone really needs this.

Related labels:
php
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