This article will share with you two practical functions of php for implementing the blacklist and whitelist, namely the security IP detection function and the function for obtaining the Client IP address, I will not talk nonsense here.
This article will share with you two practical functions of php for implementing the blacklist and whitelist, namely the security IP detection function and the function for obtaining the Client IP address, I will not talk nonsense here.
This is a php function used to check whether ip addresses are illegal. It is applicable to the Development of white list and blacklist functions. It is mainly used in api source restrictions and access restrictions.
The Code is as follows:
/**
* Security IP detection: supports IP Segment Detection
* @ Param string $ ip address the IP address to detect
* @ Param string | array $ ips IP address whitelist or blacklist IP Address
* @ Return boolean true: the value is in the whitelist or blacklist; otherwise, the value is not in the blacklist.
*/
Function is_safe_ip ($ ip = "", $ ips = ""){
If (! $ Ip) $ ip = get_client_ip (); // obtain the Client IP Address
If ($ ips ){
If (is_string ($ ips) {// use "," for example, whitelist ip: 192.168.1.13, 123.23.23.44, 193. 134 .*.*
$ Ips = explode (",", $ ips );
}
} Else {// read the White List IP address configured in the background
$ Obj = new Setting ();
$ Ips = explode (",", $ obj-> getConfig ("whiteip "));
}
If (in_array ($ ip, $ ips )){
Return true;
}
$ Ipregexp = implode ('|', str_replace (array ('*','. '), array (' \ d + ','\. '), $ ips ));
$ Rs = preg_match ("/^ (". $ ipregexp. ") $/", $ ip );
If ($ rs) return true;
Return;
}
Obtain the IP address. Here, the built-in thinkphp function is referenced.
The Code is as follows:
// Post the get_client_ip () function at the user's request
/**
* Obtain the Client IP Address
* @ Param integer $ type return type 0 return IP address 1 return IPV4 address number
* @ Param boolean $ adv whether to obtain the advanced mode (may be disguised)
* @ Return mixed
*/
Function get_client_ip ($ type = 0, $ adv = false ){
$ Type = $ type? 1: 0;
Static $ ip = NULL;
If ($ ip! = NULL) return $ ip [$ type];
If ($ adv ){
If (isset ($ _ SERVER ['HTTP _ X_FORWARDED_FOR ']) {
$ Arr = explode (',', $ _ SERVER ['HTTP _ X_FORWARDED_FOR ']);
$ Pos = array_search ('unknown ', $ arr );
If (false! ==$ Pos) unset ($ arr [$ pos]);
$ Ip = trim ($ arr [0]);
} Elseif (isset ($ _ SERVER ['HTTP _ CLIENT_IP ']) {
$ Ip = $ _ SERVER ['HTTP _ CLIENT_IP '];
} Elseif (isset ($ _ SERVER ['remote _ ADDR ']) {
$ Ip = $ _ SERVER ['remote _ ADDR '];
}
} Elseif (isset ($ _ SERVER ['remote _ ADDR ']) {
$ Ip = $ _ SERVER ['remote _ ADDR '];
}
// Valid IP address verification
$ Long = sprintf ("% u", ip2long ($ ip ));
$ Ip = $ long? Array ($ ip, $ long): array ('0. 0.0.0 ', 0 );
Return $ ip [$ type];
}
The above is all the content in this article. I hope it will help you understand php IP detection.