masteryupa
masteryupa

Reputation: 101

How to password_verify() with hash from database

Attempting to verify the hash password from the database, with the user input via POST. After some brief research it seems the issue may have something to do with not being able to convert the mysqli_query to a string though I do not know how to do that properly, hence the fetch_object() etc which I added from another SO question. I have also adequately accounted for the length of the has with the column set for varchar(255). Appreciate any help or guidance, thanks.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$password = $_POST['password'];
$db_password = mysqli_query($conn, 'SELECT password FROM sec')->fetch_object()->password;

if (password_verify($password, $db_password)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

Upvotes: 1

Views: 989

Answers (2)

Ninju
Ninju

Reputation: 2522

First get the password hash from the database,then convert the user input password in the hash value.Compare these two values by passing through the function password_verify(), then you will get the proper result.

Upvotes: 1

Gorakh Yadav
Gorakh Yadav

Reputation: 302

    $password = "test";

    $hash = "$2y$10$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e";



    if (password_verify($password, $hash)) {
        echo "Success";
    }
    else {
        echo "Error";
    }

OR
You can use this one too
$verify=password_verify($_POST['passwrd'],$row[2]);

if($verify){
    $_SESSION["usrname"]=$usrname;
    echo "Correct";
}
else {
    echo "user: " . $usrname. "<br>";
    echo "pass: " . $hash. "<br>";
    echo "db: " . $row[2]."<br>";
    echo "Wrong Username or Password";
}

Upvotes: 0

Related Questions