I’m trying to make a simple login script that will check the inputted username and password against a .txt file. The problem I have found is that my script only checks the FIRST LINE of my .txt file. That is, if the first line of the .txt file reads “test|test123” and I enter “test” as the username and “test123” as the password, everything works. However, when I do the same with the rest of my lines, it returns the “invalid password or username” statement. I believe my script is not checking other lines in my .txt file against the inputted username and password? How can this be fixed?
<?php
$check = 0;
if (isset($_POST['submit']))
{
$username = htmlentities($_POST['name']);
$username = strtolower($username);
$password = htmlentities($_POST['apw']);
$filename = getcwd() . "/atextfile.txt";
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
foreach($lines as $key => $line)
{
list($name, $pw) = explode('|', $line);
if($name == $username && $pw == $password)
$check++;
break;
}
if ($check == 1){
header("location: index.php");
}
else{
printf("Your username or password are invalid. Please try again.");
}
}
?>
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
Username:<br />
<input type = "text" id="name" name="name" size="20" maxlength="40" />
</p>
<p>
Password:<br />
<input type = "password" id="apw" name="apw" size="20" maxlength="40" />
</p>
<input type="submit" id="submit" name ="submit" name ="submit" value="Log in" />
<p>
<a href="register.php">Register</a></p>
</form>
This is your problem:
It should be