Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP login with hashed passwords

Tags:

php

mysql

hash

As the title suggests, I am having trouble logging users in, after hashing their passwords in the signup form. I have used PHP's built in password_hash() and password_verify() functions, but its on signin.php, where password_verify() is used that I am having trouble. I know that a parameter to password_verify() is a hash, but how do I use the same hash generated and stored in signup.php, to be able to use in this function?

NOTE: Yes there is more to both of these sets of code! Database connection works, all variables not defined in these bits ARE defined some lines up. signup.php works perfectly and the form data, including the hashed password are successfully stored in my database.

here is the part of signup.php where the hash is implemented:

    $hash = password_hash($password, PASSWORD_DEFAULT);
    $sql = "INSERT INTO users (id, full_name, email, password, username, sign_up_date, activated) VALUES ('', '$full_name', '$email', '$hash', '$username', '$date', '1')";

and here is the part of signin.php where the (presumably same) hash is needed: $password = mysqli_real_escape_string($_POST['password']);

if (!password_verify($password, $hash)) {
    echo 'Invalid password.';
    exit;
}

$sql = "SELECT id, email, password FROM users WHERE email = '$email' AND password = '$password' AND activated = '1' LIMIT 1";
$query = mysqli_query($conn, $sql);

EDIT: I figured this out myself a day later, had to retrieve the stored hash from database using "SELECT * FROM...", and then compare that with the entered password with password_verify(). Thanks for the help nonetheless!

like image 316
t_soist Avatar asked Feb 10 '23 06:02

t_soist


1 Answers

I am note sure where exactly the problem is. You stated that you already store the hashed password (with password_hash()) in your database. So the basic workflow would be:

a) Save the hash of the password given at the registration in your database (not the cleartext password):

$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);    
$sql = "INSERT INTO users (id, full_name, email, password, username, sign_up_date, activated) VALUES ('', '$full_name', '$email', '$hash', '$username', '$date', '1')";

b) If a user tries to login you simply get the hash from the database WHERE email = '{$_POST['email']} and then use the password_verify function:

if (!password_verify($_POST['login_password'], $hash_from_database)) { exit; }

Does this help?

like image 119
puelo Avatar answered Feb 12 '23 01:02

puelo