PHP only allows specified IP to access of allows * wildcard character to filter IP
- 2021-07-07 06:45:17
- OfStack
The core function code is as follows:
/**
* Detect the accessed ip Is it allowed by the regulations ip
* Enter description here ...
*/
function check_ip(){
$ALLOWED_IP=array('192.168.2.*','127.0.0.1','192.168.2.49');
$IP=getIP();
$check_ip_arr= explode('.',$IP);// To be detected ip Split into arrays
# Limit IP
if(!in_array($IP,$ALLOWED_IP)) {
foreach ($ALLOWED_IP as $val){
if(strpos($val,'*')!==false){// Found to have * Sign substitute
$arr=array();//
$arr=explode('.', $val);
$bl=true;// Used to record whether there is a successful match in loop detection
for($i=0;$i<4;$i++){
if($arr[$i]!='*'){// Not equal to * It is necessary to come in for testing. If it is * Symbol substitutes are not checked
if($arr[$i]!=$check_ip_arr[$i]){
$bl=false;
break;// Terminate the inspection of this ip Keep checking 1 A ip
}
}
}//end for
if($bl){// If it is true You find a 1 If the match is successful, it will return
return;
die;
}
}
}//end foreach
header('HTTP/1.1 403 Forbidden');
echo "Access forbidden";
die;
}
}
* Obtain access to IP
* 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"]);
}
Add the call check_ip () where it needs to be detected; That is enough; This function only allows the specified IP to access the file, and provides a * wildcard character in IP to match multiple IP