问题
I am using password_hash
to store passwords in a MySQL database field of type VARCHAR(255). When I try to login the user and verify credentials, the password_verify
function always returns false.
Here is the code excerpt that stores the password in the MySQL database:
$password_hash = password_hash($password, PASSWORD_DEFAULT);
// Generate API Key
$api_key = $this->generateApiKey();
// Insert Query
$stmt = $this->conn->prepare("INSERT INTO user(email, password, name, api_key, status) values(?, ?, ?, ?, 1)");
$stmt->bind_param("ssss", $email, $password_hash, $name, $api_key);
$result = $stmt->execute();
$stmt->close();
And the piece of code that checks the password:
// Query user by email
$stmt = $this->conn->prepare("SELECT password FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($password_hash);
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Found user with that email address
// Now verify the password
$stmt->fetch();
$stmt->close();
if (password_verify($password, $password_hash)) {
// User password is correct
return TRUE;
Then I wrote this test code and grabbed the data straight from the MySQL field and it still fails. When I create the password_hash in the same file ($hash2 in the file below) - then the password verifies correctly.
$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = password_hash($password, PASSWORD_DEFAULT);
echo $hash . " - " . strlen($hash);
echo "<br />";
echo $hash2 . " - " . strlen($hash2);
echo "<br />";
if (password_verify($password, $hash)) {
echo "Password Valid!";
} else {
echo "Password invalid!";
}
echo "<br /><br />";
if (password_verify($password, $hash2)) {
echo "Password 2 Valid!";
} else {
echo "Password 2 invalid!";
}
回答1:
This proves that something is wrong with your hash
<?php
// See the password_hash() example to see where this came from.
$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = '$2y$10$gMJKYZUc1FKSZBnsONxLOebOHj.uuEWSiCP0jo4Zv0iAHBz6iz.NG';
if (password_verify('pass1234567890', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
echo "<br>";
if (password_verify('pass1234567890', $hash2)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
Screenshot
来源:https://stackoverflow.com/questions/28666597/php-password-hash-and-password-verify-not-working-with-mysql