-1

我正在尝试列出在我的 htaccess 中列出的 IP 被拒绝。我不想看到deny from allor allow from

示例 IP 列表:

<files .htaccess>
order allow,deny
deny from all
</files>

allow from 10.10.190.187
deny from 10.10.76.194
deny from 10.10.85.70
deny from 10.10.63.174
deny from 10.10.56.77
deny from 10.10.15.196

期望的输出:

deny from 10.10.76.194
deny from 10.10.85.70
deny from 10.10.63.174
deny from 10.10.56.77
deny from 10.10.15.196

注意allow from 10.10.190.187deny from all从所需的输出中排除。

我当前的代码:

$htaccess = $_SERVER["DOCUMENT_ROOT"]."/.htaccess";
$file = $htaccess;
$contents = file_get_contents($file);
$lines = explode("\n", $contents); // this is your array of words
foreach($lines as $line) {
   if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $line, $ip_match)) {
   $ip =  $ip_match[0];
}
$pattern = "/deny from $ip/";
   if (preg_match_all($pattern, $line, $ip_denymatch)) {
      foreach($ip_denymatch[0] as $ipL){
         echo $ipL . "<br>"; 
   }
  }  
}

当前输出样本为:

deny from
deny from 10.10.76.194
deny from 10.10.85.70
deny from 10.10.63.174
deny from 10.10.56.77
deny from 10.10.15.196

输出包括deny from all.

4

2 回答 2

2

当您阅读 line:deny from all时,第一个preg_match返回 false 并且$ip为空。

然后,当您调用preg_match_allwith时$pattern = "/deny from $ip/";,该行匹配。

你应该使用一个preg_match像:

foreach($lines as $line) {
    if (preg_match('/^deny from \d{1,3}(?:\.\d{1,3}){3}$/', $line)) {
        echo $line,"\n";
    }
}
于 2021-08-31T08:20:07.297 回答
0

file函数易于使用,可以将文件逐行读取到数组中。

$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

preg_grep非常适合使用正则表达式过滤数组。

$arrDeniedIps = preg_grep('/^deny from [0-9.]+/',$lines);
于 2021-08-31T08:27:48.867 回答