PHP restricts IP access and only allows access from specified IP addresses
/**
- * Check whether the Accessed ip address is a specified allowed ip address.
- * Enter description here...
- */
- Function check_ip (){
- $ ALLOWED_IP = array ('192. 192. 2. * ', '192. 0.0.1', '192. 168.2.49 ');
- $ IP = getIP ();
- $ Check_ip_arr = explode ('.', $ IP); // split the ip address to be detected into an array.
- # IP address restriction
- If (! In_array ($ IP, $ ALLOWED_IP )){
- Foreach ($ ALLOWED_IP as $ val ){
- If (strpos ($ val ,'*')! = False) {// A * replacement character is found
- $ Arr = array ();//
- $ Arr = explode ('.', $ val );
- $ Bl = true; // used to record whether matching is successful in loop detection
- For ($ I = 0; $ I <4; $ I ++ ){
- If ($ arr [$ I]! = '*') {// It is not equal to * and will be checked in. if it is a * symbol replacement, it will not be checked.
- If ($ arr [$ I]! = $ Check_ip_arr [$ I]) {
- $ Bl = false;
- Break; // terminate the check. this ip address continues to check the next ip address.
- }
- }
- } // End
- If ($ bl) {// if it is true, if it is found that a match is successful, return
- Return;
- Die;
- }
- }
- } // End foreach
- Header ('http/1.1 403 Forbidden ');
- Echo "Access forbidden ";
- Die;
- }
- }
/**
- * Obtain the Accessed IP address
- * Enter description here...
- */
- Function getIP (){
- Return isset ($ _ SERVER ["HTTP_X_FORWARDED_FOR"])? $ _ SERVER ["HTTP_X_FORWARDED_FOR"]
- :( Isset ($ _ SERVER ["HTTP_CLIENT_IP"])? $ _ SERVER ["HTTP_CLIENT_IP"]
- : $ _ SERVER ["REMOTE_ADDR"]);
- }
Call Method: Add check_ip (); to the required file to achieve the IP address access restriction. This function allows only the specified IP address to access the file, the wildcard character * in the IP address matches multiple IP addresses. |