How to filter IP blacklist and whitelist using php

Source: Internet
Author: User
How to filter IP blacklist and whitelist using php

  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. }

After the core function ip_test is implemented, the following process is much simpler. it is nothing more than simply traversing each rule in the list to determine whether the IP address of the current connection meets the rule, and perform the corresponding steps. Whitelist. when the IP address must meet at least one rule, perform the following operations:

  1. $ Curr_ip = $ _ SERVER ['remote _ ADDR '];
  2. $ White_list = array (...); // whitelist rule
  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 ');

Blacklist. if the IP address does not meet all the rules, continue the operation:

  1. $ Curr_ip = $ _ SERVER ['remote _ ADDR '];
  2. $ Black_list = array (...); // blacklist rule
  3. Foreach ($ black_list as $ iprule ){
  4. If (ip_test ($ curr_ip, $ iprule )){
  5. Exit ('IP in black list ');
  6. }
  7. }

So far, a simple php ip blacklist and whitelist filtering is complete, hoping to help you. Articles you may be interested in:

PHP Security filter code (360 high security factor) PHP filter post, get sensitive data instance code php filter illegal and special string method php anti-injection of a piece of code (filter parameters) very useful php prevent SQL injection vulnerability filter function code php prevent SQL injection regular filter a piece of php filter dangerous html code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.