你知道一个简单的PHP脚本在ip检查后抛出403吗?

ams*_*raf 5 php arrays security http-status-code-403

我有一个脚本,支付处理器附带付款确认.为了使页面安全,因为它可以访问订单信息和其他用户相关的东西,我不得不通过ip(/ 24)来限制访问,如下所示:

$ipAllowed = array(
'192.192.192',
'172.172.172'
);
$ipAllowed = str_replace(".", "\.", implode("|", $ipAllowed));

if(!preg_match("/^($ipAllowed)\.[0-9]{1,3}$/", $_SERVER['REMOTE_ADDR'])){
     header('HTTP/1.0 403 Forbidden');
     die('You are not allowed to access this file.');
}
Run Code Online (Sandbox Code Playgroud)

*ip就是一个例子

在我用之前:

if(!in_array(@$_SERVER['REMOTE_ADDR'], array('ips here'))); //only works with full ip
Run Code Online (Sandbox Code Playgroud)

!in_array比我现在使用的那个更整洁,但我需要一些适用于/ 24 ips的东西,甚至两者都适用!

你知道更好/更快,可靠和更整洁的东西吗?

@ rap-2-h如你所说,这是适用于全ip,/ 24甚至/ 16的整洁版本

$ipAllowed = array( '192.168.1.153' '172.172.172'); 
$allowed = false; 

foreach($ipAllowed as $ip): 
    if(strpos($_SERVER['REMOTE_ADDR'], $ip) === 0) $allowed = true; 
endforeach; 

if (!$allowed) { 
    header('HTTP/1.0 403 Forbidden'); 
    die('You are not allowed to access this file.'); 
}
Run Code Online (Sandbox Code Playgroud)

rap*_*2-h 13

你可以尝试这样的事情:

$ipAllowed = array('192.192.192', '172.172.172');

$allowed = false;
foreach($ipAllowed as $ip) {
     if (strpos($_SERVER['REMOTE_ADDR'], $ip) !== false) {
         $allowed = true;
     }
}
if (!$allowed) {
    header('HTTP/1.0 403 Forbidden');
    die('You are not allowed to access this file.');     
}
Run Code Online (Sandbox Code Playgroud)

所以你的$ipAllowed数组中只能有ip片段.它不是很优雅,但它应该工作......