哈希和密码_verify

时间:2015-05-26 16:23:33

标签: php hash login passwords verification

我正在处理我的小PHP项目,并且我尝试在注册时实施哈希,我需要在用户想要登录时验证我的哈希密码。我尝试了很多,但我没有&#39 ;我真的知道如何在我的代码中使用password_verify函数。

在我的registration.php中,我有一个代码:

$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];

我的login.php文件如下所示:

$username = $_POST['username'];
        $password = $_POST['password'];

        $username = htmlentities($username, ENT_QUOTES, "utf-8");
        $password = htmlentities($password, ENT_QUOTES, "utf-8");

            if ($result = @$connect_db->query(sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'",
                mysqli_real_escape_string($connect_db, $username),
                mysqli_real_escape_string($connect_db, $password)))
            ) {
                $amount = $result->num_rows;
                if ($amount > 0) {
                    $_SESSION['logged_in'] = true;

                    $row = $result->fetch_assoc();
                    $_SESSION['user_id'] = $row['user_id'];
                    $_SESSION['username'] = $row['username'];
                    $_SESSION['enter code hereemail'] = $row['email'];
                    $_SESSION['admin'] = $row['admin'];

                    unset($_SESSION['error']);
                    $result->free_result();
                    header('Location: dictionary.php');
                } else {
                    $_SESSION['error'] = '<p class="error_m">Invalid username or password!</p>';
                    header('Location: index.php');
                }
            }

我的问题是关于如何在login.php文件中使用password_verify函数?

2 个答案:

答案 0 :(得分:1)

password_hash()的结果存储在数据库中时,您将存储哈希密码。要检查输入的密码是否正确以登录用户,您可以执行以下操作(伪代码):

$result = $db->getAssoc("SELECT password FROM users WHERE username='".$username."'");
if ($result) { 
   if(password_verify($password, $result['password']){
        //log the user in
    }
}

http://php.net/manual/en/function.password-verify.php

答案 1 :(得分:0)

您不会将用户键入的密码哈希到表单中,而是在用户实际注册到您的站点时对密码进行哈希

.main-menu:hover,
nav.main-menu.expanded {
    width: 250px;
  transition: width .5s linear;
}

登录过程以及如何使用password_verify功能

$password = filter_var($_POST['aPass'] , FILTER_SANITIZE_STRING) ;
$newPassword = password_hash($password , PASSWORD_DEFAULT);
// input $newPassword into the database.

你还应该看一下mysqli预备语句