尝试使用普通 PHP 开发中间件时出错


Error trying to develop middleware using vanilla PHP

我似乎无法让它工作。它获取 json 和所有内容,它只是不想检查请求 IP。

$wl_loc = "whitelist.json";
$wl = json_decode(file_get_contents($wl_loc), TRUE);
function get_client_ip_server() {
    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}
$urip = get_client_ip_server();
foreach($wl as $arr) {
  $ip = $arr['ip'];
  if($urip == $ip) {
    header("Location: /maintenance/");
  }
}

和我的白名单.json

[
  {
    "ip": "0.123.456.789"
  },
  {
    "ip": "123.456.789.0"
  }
]

我已经为此苦苦挣扎了几个小时,在互联网上到处寻找,我一无所获。我想要实现的是它遍历每个 IP,然后检查请求 IP,如果为 true,则不要重定向,否则如果为 false,则重定向。

尝试下面的代码,

$newArray   = array();
$myCallback = function($key) use(&$newArray){
  $newArray[] = $key["ip"];
};
array_walk($wl, $myCallback);
$urip = get_client_ip_server();
if(!in_array($urip, $newArray)) {
    header("Location: /maintenance/");
}

一个简单的逻辑在这里起作用,

从主数组中创建了一个新数组,该数组在单个维度中仅包含 IP,其余的由 if 语句使用