PHP Read txt file and check if username password exists

送分小仙女□ 提交于 2019-12-14 03:35:18

问题


I have a bunch of passwords and usernames stored in a txt file and i need to check for matches. I know this is not a safe method but its for leaning purposes.

This code writes the usernames and passwords to a txt file

  if(isset($_POST['register'])) //  
   {
    $user  = $_POST['username'];
    $password=$_POST['password'].PHP_EOL;
    $fh = fopen("file.txt","a+");
    fwrite($fh,$user." ".$password); //write to txtfile

    fclose($fh);
 }

Here's the code im having trouble with.

Username and Passwords are stored like this in results

      username1 passwords1 username2 password2 etc. 

So I need to check if result[0] = userinput AND if it exists check if result[1] = passwordInput and so on.

   if(isset($_POST['Logg']))
   {
   //$_SESSION['username']=$user; 
   //$_SESSION['password']=$password;

    $file = file_get_contents("file.txt"); // Returns a string

    $result = explode(" ",$file);
    $boolC= false;

    for($i=0; $i< count($result); $i++)
    {
   if($result[$i] === $user)
   {
    $boolC=true;
    $i =$i+1; 
    if($boolC === true)
    {
        if($result[$i]===$password)
        {
            echo 'Password and Username Correct';
        }
    }

   }
     }

  }

回答1:


Consider the possibility of having a space in the password so as any symbols. Perhaps you should split on a line break ("\n").

if( $result[$i] === $user && $result[$i+1] === $password )

The first part of the statement has to be true for the second one to be evaluated. The $i variable is never changed

$file = "username1 passwords1 username2 password2";
$result = explode(" ",$file);
$user = "username1";
$password = "passwords1";

for($i=0; $i< count($result); $i++){

    if($result[$i] === $user && $result[$i+1] === $password)
    {

        echo 'Password and Username Correct';
   }
}



回答2:


Before you go ahead and try to correct this code, I strongly suggest you stay away from storing passwords in a plain text file. It is a huge security hole in your system.

Another architecture issue I can see is that your code would fail if the username or passwords contain a space in them. You probably should use line jumps as a delimiter instead (\n).




回答3:


I think there is nothing wrong with the logic of the original post.

You should print all the variables to check whether they hold the correct value or not.

the "$user" and "$password" variables are global or not since they would not be known within the braces of the other if block i.e in the block where you check $_POST['logg']



来源:https://stackoverflow.com/questions/15189470/php-read-txt-file-and-check-if-username-password-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!