gpt4 book ai didi

PHP password_hash 和 password_verify 不适用于 MySQL

转载 作者:行者123 更新时间:2023-11-29 00:03:25 25 4
gpt4 key购买 nike

我正在使用 password_hash 将密码存储在 VARCHAR(255) 类型的 MySQL 数据库字段中。当我尝试登录用户并验证凭据时,password_verify 函数总是返回 false。

这是将密码存储在 MySQL 数据库中的代码摘录:

$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();

还有一段检查密码的代码:

// 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;

然后我写了这段测试代码,直接从MySQL字段中抓取数据,还是不行。当我在同一个文件中创建 password_hash(下面文件中的 $hash2)时 - 然后密码验证正确。

$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!";
}

最佳答案

这证明你的哈希有问题

<?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.';
}

截图enter image description here

关于PHP password_hash 和 password_verify 不适用于 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com