Search code examples
phpphp-7.4

I wonder a php 7.4 giving me trouble on login script


Problem is occurring when no user exists because PHP 7.4 returns false here on $fetched = $check->fetch();

so how to handle this situation

    $name = $_POST['name'];
    $pass = $_POST['pass'];
    $check = $db->prepare("SELECT id, name, pass FROM users WHERE name = ?");
    $check->execute([$name]);
    $fetched = $check->fetch();
    if (password_verify($pass, $fetched['pass']) && ($name === $fetched['name']){
        header('Location: home');
    } else {
        echo 'This account not exists';
    }

but I don't know why this work without password_verify(), look

if ($check->rowCount() > 0 ) {

} else {

}

Solution

  • Add a check for $fetched:

    if ($fetched && password_verify($pass, $fetched['pass'])) {
        header('Location: home');
    } else {
        echo "Invalid username or password";
    }
    

    There's no need to test $fetch['name']. It's guaranteed to be equal to $name because of WHERE name = ?