Youmna
Youmna

Reputation: 15

I'm having log in issues using bcrypt

I apologize in advance if this is a stupid question or if it's in the wrong place. This is my first time here. I've been stuck on this all day and I can't seem to fix the problem. I've never used bcrypt before but I followed several online tutorials and I was able to create a functioning sign up page. Here's the encryption code:

$password = password_hash($password, PASSWORD_DEFAULT)."\n";

The sign up page works perfectly and the passwords are encrypted in the database. From my understanding, in the sign in page what happens is that we use a Select statement to get the hashed password for the username/email the user enters and then we use password_verify. So here's my code:

$email = $_POST['user_email'];
$password = $_POST['user_password'];


$stmt = $db->prepare("SELECT Password FROM user WHERE Email= :email");
$stmt->execute(array(':email' => $email));
$hash = $stmt->fetchColumn(0);

if (password_verify($password, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

For some reason, it still keeps saying "Invalid Password". I tried printing the hash that the select statement returns to make sure it is the one in the DB and it is. I also tried copying the hash and placing it in password_verify to try and find out what the problem is but it still won't work. Do you have any ideas for me?

Thanks everyone :o)

Upvotes: 1

Views: 294

Answers (1)

user3942918
user3942918

Reputation: 26375

When you generate the hash, don't append a newline to it with ."\n" I'm pretty sure you're saving it to the database with that. It'll appear fine when printed but never verify.


Working:

$password = 'test';
$hash = password_hash($password, PASSWORD_DEFAULT);

if (password_verify($password, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Output:

Password is valid!

Upvotes: 2

Related Questions