Jump to content

fgets(), me again


lewashby

Recommended Posts

In the following program I need to step through a text file line by line checking to see if an email address and then a password are present. It currently works for the first entry in the accounts.txt file but fails if I try the second entry in the form. Any ideas?

<?php

$email = $_POST['email'];
$psswd = $_POST['psswd'];

$db = new SQLite3('./users.db', SQLITE3_OPEN_READWRITE);

if(!$db)
{
    echo "Could not open/access DB";
}
else
{
    $result = $db->query("SELECT email, password FROM users WHERE email='$email'");
    $user = $result->fetchArray();

    if(!$user)
    {

        $file = fopen("./accounts.txt", 'r+') or die("Failed to open file");

        while(!feof($file))
        {
            $line = fgets($file);
            if(strpos($line, "$email") !== false)
            {
            if(strpos($line, "$psswd") !== false)
            {
            header("location: ./changepassword.html");
            break;
        }
        else
        {
            echo "Invalid password";
            break;
        }
        }
        else
        {
            echo "Invalid email address";
        break;
        }
    }
            
        fclose($file);
    }
    else
    {
    if($psswd == $user['password'])
        {
            echo "You have already changed your password";
        }
    }

}
?>
Link to comment
https://forums.phpfreaks.com/topic/282590-fgets-me-again/
Share on other sites

I breaks are only there when a match is found to keep the loop from continuing after I have my banana.

No, you break in all three cases: Found, Email-mismatch, and password-mismatch. What you WANT is to break ONLY when the email and password BOTH match, ie the entry is found.

 

For your not-found error messages, what you want to do is have a test AFTER the loop which checks to see if anything was found. You can do this by setting a $found variable to false before the loop, and setting it to true if a valid entry is found. Then after the loop check if $found is true or false. If false, print your error otherwise continue on. Do not bother with trying to print separate messages for email not found vs password doesn't match. A login system should only ever say either they login was successful, or it failed. It should not give any reason for why it failed.

Link to comment
https://forums.phpfreaks.com/topic/282590-fgets-me-again/#findComment-1452132
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.