PHP MySQL – Matching Usernames with Passwords

databaseencryptionMySQLpasswordsPHP

We are working on a simple login/registration form. Our login script checks to see if the username and password exist in the same row of the database. If it does exist, we bring the user to a welcome page.

However, our problem lies when we check to see if the password exists in the database because we have applied the password_hash() function to the user submitted password. This encryption method is one-way and not reversible (to my knowledge). Here is the code for the login script:

<?php 
//will correspond with 'loginLogin.html page
require("opendboLogin.php");
$user = $_POST['username'];
$password = $_POST['password'];

$stmt2 = $conn->stmt_init();
$stmt2 = $conn->prepare("SELECT * FROM login WHERE alogin = ? AND apassword = ?"); 
$stmt2->bind_param("ss", $user, $password);
$stmt2->execute();
$stmt2->store_result();
$numberofrows = $stmt2->num_rows; //this is an integer!!
$stmt2 -> close();

if($numberofrows > 0) //if username and password combination exists in a row 
{ 
    echo 'login successful!';
}
else
{
    echo 'Incorrect username and/or password, dumbass!';
}
?>

I was thinking perhaps we could encrypt the password AGAIN inside this script and see if the two hashes match, however the encryption changes each time regardless of whether the same exact password was hashed!

As of right now the username/password combination will never exist and will always hit the last "else" statement. Any ideas how to check for the correct username/password combination?

Best Answer

Attempt to fetch the user record based on the username (but use LIKE instead of = so that case doesn't matter. Usernames should not be case sensitive.

If you managed to fetch a user record (then the user exists) and you can compare the passwords to validate the login.

About password security

Store the passwords using a function like password_hash() so that they're far more secure than being stored plain text (a huge no-no). This will generate unique salt each time so yes the hash will be different each time. Don't worry about that.

To validate the password the user is logging in with against the stored password, use password_verify() and pass it the password they posted and the stored hash from the database. The function will take care of the salt and comparison. This is the function that I think you might've missed when reading about password hashing.

Bonus

After successful login you should check to see if the password needs re-hashed (over time the "cost" of the algorithms are updated). Simply pass the stored hash to password_needs_rehash() to see if you should re-hash and re-save the password.

Related Topic