This article has shared 2 PHP for the implementation of the black and white list of practical functions, respectively, the security IP detection function and get client IP function, the comments explained very clearly, here I do not much nonsense.
This is a PHP function to detect whether the IP is illegal, adapt to the whitelist, blacklist feature development, the main scenario applies to: API source restrictions, access restrictions and so on.
The code is as follows:
/** * Security IP detection, support IP segment detection * @param string $IP to detect IP * @param string|array $ips Whitelist IP or blacklist IP * @return boolean true on white list or black list, otherwise not */function is_safe_ip ($ip = "", $ips = "") { if (! $ip) $ip = Get_client_ip (); Gets the client IP if ($ips) { if (is_string ($ips)) {//IP with "," for example, whitelist ip:192.168.1.13,123.23.23.44,193.134.*.* $ips = Explode (",", $ips); } } else{//Read background configuration whitelist IP $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;}
Get IP address, reference thinkphp built-in function here
The code is as follows:
At the request of users, posted get_client_ip () function/** * Get the client IP address * @param integer $type return type 0 returns the IP address 1 returns the IPV4 address number * @param Boolean $adv whether high Level mode acquisition (possibly 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_forwa Rded_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 ']; }//IP address legal authentication $long = sprintf ("%u", Ip2long ($IP)); $ip = $long? Array ($ip, $long): Array (' 0.0.0.0 ', 0); return $ip [$type];}
Summary : The above is the entire content of this article, I hope to be able to help you learn.