Search code examples
phphashpassword-hash

password_verify does not seem to work


I'm completely new to the password_hash and verify functions, but I've read the documentations about them on the default php website. I have problems with logging in when I hash passwords using password_hash. They are already hashed in the database.

This is my code I use to verify if the password entered in the form matches with the hash in the database (that has been generated with password_hash in a register form):

    $username = $kunaiDB->real_escape_string($_POST["uname"]);
    $password = $kunaiDB->real_escape_string($_POST["pword"]);

    $kunaiLoginQuery = "SELECT * FROM kunai_users";

    $kunaiLoginQueryResult = $kunaiDB->query($kunaiLoginQuery);
    $controlhash = $kunaiLoginQueryResult->fetch_array();
    $db_pw_res = $controlhash["user_pw"];

    if(password_verify($password, $db_pw_res)) {
        echo "Passwords match!";
    } else { echo "Passwords do not match!"; }

Whenever I log in it fails. I've tried to search for similar solutions but so far I've not found anything that worked. All help is appreciated :-)


Solution

  • Their is mistake in your SQL query. Add a WHERE clause. Something like this

    SELECT * from table_name WHERE user_name_field = '{$username}'
    

    And instead of

    $controlhash = $kunaiLoginQueryResult->fetch_array();
    

    Type

    $controlhash = $kunaiLoginQueryResult->fetch_assoc();