且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用PHP的password_hash哈希和验证密码

更新时间:2023-10-21 19:45:28

建议使用password_hash存储密码.不要将它们分离为数据库和文件.

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

假设我们输入以下内容:

Let's say we have the following input:

$password = $_POST['password'];

我不仅仅为了理解概念而验证输入.

I don't validate the input just for the sake of understanding the concept.

您首先通过执行以下操作对密码进行哈希处理:

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

然后查看输出:

var_dump($hashed_password);

如您所见,它是散列的. (我假设您已执行这些步骤).

As you can see it's hashed. (I assume you did those steps).

现在,您将此hashed_pa​​ssword存储在数据库中,确保您的password列足够大以容纳哈希值(至少60个字符或更长).当用户要求登录时,您可以通过执行以下操作在数据库中检查带有此哈希值的密码输入:

Now you store this hashed_password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

官方参考