接受用户输入的密码并检查它是否与存储在MySQL数据库表中的散列密码匹配的基本代码是什么?
这是一个基本的非安全示例,说明如何验证用户输入的密码是否与存储在数据库中的password_hash版本匹配。我写这个问题是因为我在网上找不到一个基本的可以理解的答案。
要对此进行测试,需要一个数据库连接、一个包含数据的名为user
的数据库表(当然)和一个错误页面(这里是error.html.php)。
我希望这对你有帮助。
<?php
if(isset($_POST['action']) && $_POST['action'] === 'submit')
{
include 'your database connection file';
try
{
$sql = 'SELECT password FROM user
WHERE email = :email';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $_POST['email']);
$s->execute();
}
catch(PDOException $e)
{
$error = 'Error fetching password.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Assign single row result to $result as associative array
$result = $s->fetch(PDO::FETCH_ASSOC);
// Check for match using boolean password_verify()
if(password_verify($_POST['password'], $result['password']))
{
echo '<p style="color:#0000ff">Match!</p>';
}
else
{
echo '<p style="color:#ff0000">Sorry, wrong password.</p>';
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Password Verify</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="email" placeholder=" Email">
<input type="text" name="password" placeholder=" Password">
<button type="submit" name="action" value="submit">Submit</button>
</form>
</body>
</html>