How to make encrypted password queries in the database?

Asked

Viewed 275 times

0

Well, I created a function called search party that should encrypt the user’s password and compare it with the database but every time I run I get the error:

Warning: mysqli_fetch_assoc() expects Parameter 1 to be mysqli_result, Boolean Given in C: xampp htdocs filename database.php on line 9

Function

function buscaUsuario($conexao, $email, $senha){
    $hash = password_hash($senha, PASSWORD_DEFAULT);
    $query = "select * from usuarios where email='{$email}, senha='{$hash}'";
    $resultado = mysqli_query($conexao, $query);
    $usuario = mysqli_fetch_assoc($resultado);
    if(password_verify($usuario, $hash)){
        echo "Valid";
    } else {
        echo "invalid";
    }
    return $usuario;
 }

How could I make this function compare the generated Hash with the hash that is in the database and still confirm if the login has been validated or invalid?

I was thinking of having my database return the registered value in the password field assigning it to a variable so I can use the password_verify($user_senha, $hash) and check if the user generated hash is the same as the one registered in the database. Would it work? If so, how?

1 answer

3


Your sweetheart seems to have a syntax error.

It’s like this :

"select * from usuarios where email='{$email}, senha='{$hash}'";

The right thing would be :

"select * from usuarios where email='{$email} AND senha='{$hash}'";

Taking into account that in the user registration you have saved in your table the hash generated by the function password_hash, the corrected script would look like this:

function buscaUsuario($conexao, $email, $senha){
    $query       = "select * from usuarios where email='".$email."'";
    $resultado   = mysqli_query($conexao, $query);
    $row_cnt     = mysqli_num_rows($resultado);
    if($row_cnt > 0){
        $usuario = mysqli_fetch_assoc($resultado);
        /*$senha é o valor digitado pelo usúario e o $usuario['hash'] salvo 
        anteriormente no banco de dados*/
        if(password_verify($senha, $usuario['hash'])){
            echo "Valid";
            return $usuario;
        }else{
           echo "invalid";
           return false;
       }
    }else{
       echo "Não existem usuários com o login informado.";
       return false;
    }
}

Credits by correction to @Inkeliz, improve and adapt to your taste!

  • 2

    The correct thing would be to remove the AND senha='{$hash}', because Bcrypt has a whole salt, which will cause the $hash always be different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.