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 IP address to be detected * @ param string | array $ ips White List IP address or black list IP address * @ return boolean true in the white list or black list, otherwise, it is not in */function is_safe_ip ($ ip = "", $ ips = "") {if (! $ Ip) $ ip = get_client_ip (); // Obtain the client IP if ($ ips) {if (is_string ($ ips) {// ip address ", "For example, whitelist IP address: 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 get_client_ip () at the user's request () function/*** get client IP address * @ param integer $ type return type 0 return IP address 1 return IPV4 address number * @ param boolean $ adv whether to perform advanced mode acquisition (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.