我如何从txt文件中读取两行,并将这两行与我存储在变量中的内容进行比较


how do I read two lines from a txt file and compare those two with what I have stored in variables

我已经有了user.txt文件,其中包含一个用户。用户名为Admin,密码为123。我想做的是,如果这两个在文件的中间位置,可以找到并比较它们是否都是正确的,因此标志将等于1。

这是我到目前为止的代码。

<?php 
session_start();  
$_SESSION[name] = $_POST[name];
$_SESSION[pass] = $_POST[pass];
$flag= 0;
if(!$fp = fopen("users.txt","r")) { 
    echo "Error 404"; 
} 
else { 
        while(!feof($fp)){
            $line1= fgets($fp,10);
            $line2= fgets($fp,10);
            if($line1== $name && $line2 == $pass)
                $ban = 1;
        }
    fclose($fp);
}
if($flag == 1){
        ?>
        <html>
            <head>
                <meta http-equiv="refresh" content="3; url= access.php">   
            </head>
         </html>
         <?php
}
else{
        ?>
        <html>
            <head>
                <meta http-equiv="refresh" content="3; url= login.html">   
            </head>
         </html>
         <?php
} 
?>

我个人会考虑使用file_get_contents,这取决于您的文件有多大。

 // <= PHP 5
 $file = file_get_contents('./users.txt');
 // > PHP 5
 $file = file_get_contents('./users.txt');
 if(strpos('Admin') !== false){ if(strpos('123') !==false){ //ACTIONS WHEN USERNAME IS PRESENT } }

如果您需要更具体,您可以告诉file_get_contents从某个字符开始读取,并继续X行。更多信息请点击这里。

如果你不确定文件有多大,那么你可以使用其他方法来确定有多少行,然后除以2,从中间开始。这个问题包含了大部分信息,如果你想了解更多,请告诉我。

最后,我想知道为什么你想要基于文本文件进行身份验证。如果您想要平面解决方案,我建议使用ini文件,但我相信您有自己的理由。:)

为了以防万一,这里有关于ini的信息