如何验证用户输入的密码是否与存储在MySQL数据库中的哈希密码匹配

时间:2015-09-16 13:26:56

标签: php mysql

用户输入密码并检查它是否与存储在MySQL数据库表中的散列密码相匹配的基本代码是什么?

1 个答案:

答案 0 :(得分:0)

这是一个基本的非安全示例,说明如何验证用户输入的密码是否与数据库中存储的password_hash版本匹配。我提供此Q& A因为我无法在线找到基本可理解的答案。

要对此进行测试,您需要一个数据库连接,一个名为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>  
相关问题