如何检查文件中是否存在行


How to check if line exists in a file

我想检查文件中是否存在一行,以避免同一行重复。我已经对网站设置了开发限制,只允许自己查看它,其他人被重定向到"不可用.php"页面
但我想允许人们在请求权限时查看网站
就我而言,我有一个.htaccess文件

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REMOTE_HOST} !^34'.120'.121'.20 #this a random ip
RewriteCond %{REQUEST_URI} !path/to/first/exception'.php$ #first exception is 'unavailable.php'
RewriteCond %{REQUEST_URI} !path/to/another/exception'.php$ #the second exception is 'request_permission.php'
RewriteRule '.php$ /redirect/to/first/exception/ [L]

request_permission.php,我有以下代码:

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    $data = file('.htaccess');
    $parts = explode(' ', $data[2]);
    $parts_end = end($parts);
    $parts_substred = substr($parts_end, 2); 
    $ip_addr = str_replace('''', '', $parts_substred); 
    if ($ip_addr != $ip){
        $new_ip = str_replace('.', '''.', $_SERVER['REMOTE_ADDR']);
        $new_string = str_replace($parts_end, "", $data[2]) . "!^".$new_ip;
        $string = $data[0].$data[1].$data[2].$new_string.PHP_EOL.$data[3].$data[4].$data[5];
        //file_put_contents(".htaccess", $string);
    }
?>

现在每次我访问request_permission.php一个新行时,就像正在创建这样:RewriteCond %{REMOTE_HOST} !^56'.80'.1'.15(假设这是我的 ip)。

我想检查 htaccess 中是否存在带有我的 IP 地址的行,这样做我不会再次复制它。


我尝试使用strpos()但即使存在,它也找不到我的 IP 地址。

我应该怎么做?

我只会在preg_match()中使用正则表达式查找任何REMOTE_HOST行,然后在找不到时附加所需的行:

请注意,我完全同意其他人的意见,即这不是一个好的解决方案。我正在回答这个问题,但同时建议您寻找其他方式......

我的原始(现已删除)有一些问题 - 这个有效,尽管仍然在做我认为你不应该做的事情(为了方便起见,我只是复制整个测试脚本 - 你需要回到阅读文件):

<?php
$ip = '34.120.121.29';
$ip_pat = str_replace('.', '''''''.', $ip);
# Note that I'm using $data as a straight string, not an array - use file_get_contents() to read it
$data = <<<EOF
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REMOTE_HOST} !^34'.120'.121'.20 #this a random ip
RewriteCond %{REQUEST_URI} !path/to/first/exception'.php$ #first exception is 'unavailable.php'
RewriteCond %{REQUEST_URI} !path/to/another/exception'.php$ #the second exception is 'request_permission.php'
RewriteRule '.php$ /redirect/to/first/exception/ [L]
EOF;
$pat = '^RewriteCond *%{REMOTE_HOST} *';
if (!preg_match("/$pat.*$ip_pat/m", $data)) {
    #echo "NO MATCH<br />'n";
    $new_ip = str_replace('.', '''.', $ip);
    $new_string = preg_replace("/$pat/m", "RewriteCond %{REMOTE_HOST} !^$new_ip".PHP_EOL."$0", $data);
    #$data .= $new_string.PHP_EOL;
    echo nl2br("$new_string");
}

请注意,在调用 to preg_replace() 中使用 limit 参数时,仅替换第一个匹配项。如果你不这样做,那么你的第 3 次添加将加倍,你的第 4 次添加将翻两番,依此类推。