Php ip address and IP address segment access restriction code
Last Update:2018-12-08
Source: Internet
Author: User
192.168.1.1 Single IP Address
192.168.1. * proxy 192.168.1.1-192.168.1-255
192.158.1.2-20 represents 192.158.1.2-192.158.1.20
You can also write 192.168.1. [1 | 2 | 3]
Hey hey ~ I don't know whether the idea is comprehensive in one method. I will discuss it with you.
Use
The following is a reference clip:
$ Oblock_ip = new block_ip ();
$ Oblock_ip-> checkip ();
The following is a reference clip:
CopyCode The Code is as follows: <? PHP
Class block_ip {
VaR $ block_ip = array ("192.168.1.1", "210.10.2.1-20", "222.34.4 .*");
Function _ construct (){
}
Function _ destruct (){
}
Private function makepregip ($ Str ){
If (strstr ($ STR ,"-")){
$ AIP = explode (".", $ Str );
Foreach ($ AIP as $ K =>v v ){
If (! Strstr ($ v ,"-")){
$ Preg_limit. = makepregip ($ V );
} Else {
$ Aipnum = explode ("-", $ V );
For ($ I = $ aipnum [0]; $ I <= $ aipnum [1]; $ I ++ ){
$ Preg. = $ preg? "|". $ I: "[". $ I;
}
$ Preg_limit. = strrpos ($ preg_limit, ".", 1) = (strlen ($ preg_limit)-1 )? $ Preg. "]": ".". $ preg. "]";
}
}
} Else {
$ Preg_limit. = $ Str .".";
}
Return $ preg_limit;
}
Private function getallblockip (){
If ($ this-> block_ip ){
Foreach ($ this-> block_ip as $ k => $ v ){
$ Ipaddres = $ this-> makepregip ($ V-> start_ip );
$ IP = str_ireplace (".", "\.", $ ipaddres );
$ IP = str_replace ("*", "[0-9] {1, 3}", $ IP );
$ Ipaddres = "/". $ IP ."/";
$ Ip_list [] = $ ipaddres;
}
}
Return $ ip_list;
}
Public Function checkip (){
$ Iptable = $ this-> getallblockip ();
$ Isjoined = true;
// Obtain the user IP Address
$ IP = $ this-> get_client_ip ();
$ IP = trim ($ IP );
// Remove the IP segments in the blacklist
If ($ iptable ){
Foreach ($ iptable as $ value ){
If (preg_match ("{$ value}", $ IP )){
$ Isjoined = false;
Break;
}
}
}
// Perform the following operations in the IP blacklist:
If (! $ Isjoined ){
Echo "ip error ";
Exit;
}
}
Private function get_client_ip (){
If (getenv ("http_client_ip") & strcasecmp (getenv ("http_client_ip"), "unknown "))
$ IP = getenv ("http_client_ip ");
Else if (getenv ("http_x_forwarded_for") & strcasecmp (getenv ("http_x_forwarded_for"), "unknown "))
$ IP = getenv ("http_x_forwarded_for ");
Else if (getenv ("remote_addr") & strcasecmp (getenv ("remote_addr"), "unknown "))
$ IP = getenv ("remote_addr ");
Else if (isset ($ _ server ['remote _ ADDR ']) & $ _ server ['remote _ ADDR '] & strcasecmp ($ _ server ['remote _ ADDR'], "unknown "))
$ IP = $ _ server ['remote _ ADDR '];
Else
$ IP = "unknown ";
Return ($ IP );
}
}
?>