Demand from an operations colleague, the implementation of a PHP file IP filtering, not easy to directly configure the server, so you need to directly at the beginning of the PHP file IP filtering.
IP filtering rules can have the following form:
1. Complete IP address such as: 192.168.0.1
2. A section of IP such as: 192.168.0.*.
OPS can customize IP black-and-white lists, consisting of multiple IP filtering rules, which are stored in arrays. Implement IP black-and-white list functionality by writing code. A relatively simple requirement.
A function is first implemented to determine whether IP is compliant 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 of ip_test, the following procedure is much simpler, simply traversing each rule in the list, judging whether the IP currently connected is compliant with the rules, and doing the corresponding steps.
Whitelist, continue operation when IP satisfies at least one rule
$curr _ip=$_server[' remote_addr ']; $white _list=array (...); White list rules $test _success=false; foreach ($white _list as $iprule) { if (ip_test ($curr _ip, $iprule)) { $test _success=true; break; } } if (! $test _success) exit (' IP not at White List ');
Blacklist, continue operation when IP does not meet all rules
$curr _ip=$_server[' remote_addr ']; $black _list=array (...); Blacklist rule foreach ($black _list as $iprule) { if (ip_test ($curr _ip, $iprule)) { exit (' IP in black list ') } }
In this way, a simple PHP implementation of the IP black-and-white list filter is complete. This blog is mainly for those who do not develop the main business, such as: technical support, operations and so on. Because too simple, originally did not want to write, later that colleague thanked me to help, said to me this he looked for a long time on the net, did not find the right solution, I thought maybe this really someone needs.