gpt4 book ai didi

php - 如何从数据库验证密码

转载 作者:行者123 更新时间:2023-12-01 16:26:39 24 4
gpt4 key购买 nike

我将密码存储在数据库中,如下所示:

public function add_user($username, $password){

$password = password_hash($password, PASSWORD_DEFAULT); //here

$this->query = $this->conn->prepare('INSERT INTO users (username, password) VALUES (:username, :password)');
$this->query->bindParam(':username', $username);
$this->query->bindParam(':password', $password);
$this->query->execute();
}

但是,我不知道如何检索它。我知道这个功能

password_verify($password, $hash)

但是我不知道如何使用它。如何使用它从数据库中获取用户?

使用以下代码验证密码的最佳方法是什么:

public function get_user($username, $password){

$this->query = $this->conn->prepare('SELECT * from users WHERE username=:username AND password=:password');
$this->query->bindParam(':username', $username);
$this->query->bindParam(':password', $password);
$this->query->execute();
$this->retrieve = $this->query->fetchAll(PDO::FETCH_ASSOC);
}

任何帮助或指导都会很棒。这个逻辑让我很困惑。

最佳答案

首先,+1 使用 PHP 的密码函数进行密码哈希!

与普通的散列函数(例如 md5()sha1() 等)相反 - 不应用于密码散列),password_hash() 每次都会根据相同的密码生成不同的哈希值,因为它会自动为每个哈希值生成随机盐。这是一个很棒的功能,可以使您的密码散列更加安全,但这意味着您不能使用 password_hash() 对输入的密码进行散列,并在 SQL 查询中使用该散列密码(与用户名)来检索用户。

相反,只需根据用户名检索用户 - 然后使用 password_verify() 将检索到的密码哈希与输入的密码进行比较。即使成本或算法发生了变化,此函数也能够将输入的密码与存储的哈希值进行比较。

示例(使用您的代码):

public function get_user($username, $password)
{
$this->query = $this->conn->prepare('SELECT * from users WHERE username=:username LIMIT 1');
$this->query->bindParam(':username', $username);
$this->query->execute();
$user = $this->query->fetch(PDO::FETCH_ASSOC);

if (password_verify($password, $user['password']) {
// password is correct, return the user
return $user;
} else {
// incorrect password
return false;
}
}

future 提高密码强度

正如我之前所说,新的密码 API 允许升级新生成的密码散列的强度,而不会破坏旧的密码散列。这是因为成本和算法(顺便说一下,还有盐)存储在哈希中。

随着可用硬件变得越来越强大,建议随着时间的推移增加成本(减少攻击者暴力破解密码所需的时间)。

如果您决定这样做,或者决定使用其他哈希算法,请不要忘记使用 password_needs_rehash() 添加检查。在您的登录过程中。这样现有的密码也将被重新哈希。

如果函数(使用数据库中的哈希值作为参数调用)返回 true,只需再次运行 password_hash() 并用新哈希值覆盖数据库中的旧哈希值。显然,这只能在用户登录时完成,因为这是您应该有权访问纯文本密码的唯一时间。

关于php - 如何从数据库验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23910725/

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