6C69616D
6C69616D

Reputation: 72

How to Compare BCRYPT Hashed Passwords in PHP

I have a "create new user" form in HTML and need to know where certain parts of it need validating and checking (PHP or javascript) and the best way to go about it.

The password handling is done in PHP and so is the code that checks to see if the given username is available or already exists in the database. Need to know the best place to compare the "password" and "confirm password" fields as it seems hard to do when both are hashed in PHP.

if ($_SERVER["REQUEST_METHOD"] == "POST") { // If the form is submitted and by the method of post
    $new_username = test_input($_POST['new_username']); // Set new_username to the new_username value from the form
    $new_password = password_hash(test_input($_POST['new_password']), PASSWORD_DEFAULT); // Get the new_password from the form and hash it before passing to the variable
    $confirm_password = password_hash(test_input($_POST['new_password_confirm']), PASSWORD_DEFAULT); // Get the confirm_password field from the form and hash it
    $team = $_POST['new_team']; // Get the new_team field (doesn't need validation as it is a dropdown choice)
    $username_valid = test_account_validity($newConnection, $new_username);
    if ($username_valid) {
        echo "";
    }
    if (hash_equals($new_password, $confirm_password)) {
        echo "Passwords Match";
    }
    else {
        echo "Passwords Dont Match";
    }
}

function test_input($data) { // Function to remove spaces, slashes and special html characters before returning the valid data
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

Expected Passwords match output when the passwords are the same before hashing (same entered into both form fields) but it says the passwords don't match.

EDIT

Different from how to use password hash as this is about comparing hashes with one another for two entered passwords rather than comparing a string to a hash or hashing to store in a database.

Upvotes: 0

Views: 1634

Answers (1)

Mohamed Abdallah
Mohamed Abdallah

Reputation: 996

the scenario to login the user is

  1. get the username and password from the html
  2. get the user data that matches the username from the database
  3. pass the plain password that came from user input and the hash from the database to password_verify function, if it returns true it means the password is correct otherwise the password is wrong

see the docs php.net

Upvotes: 2

Related Questions