我正在为我的网站登录。我在创建帐户时使用password_hash()
函数,并将其作为nvarchar存储在MSSQL数据库中,长度为255。当我尝试检查用户登录时给出的密码时,它永远不会返回true。我已经查看了一些类似的问题,但无法找到能解决问题的任何问题。
密码加密:
$user_password = $_POST['user_password_new'];
// crypt the user's password with PHP 5.5's password_hash() function, results in a 60 character
// hash string. the PASSWORD_DEFAULT constant is defined by the PHP 5.5
$user_password_hash = password_hash($user_password, PASSWORD_DEFAULT);
...
// write new user's data into database
$sql = $this->db_connection->prepare("INSERT INTO users (user_name, user_password_hash, user_email)
VALUES(:username, :password, :email)");
//sanitizing data to make sure no SQL or HTML gets injected
$sql -> bindParam(':username', $user_name, PDO::PARAM_STR);
$sql -> bindParam(':password', $user_password_hash, PDO::PARAM_STR);
$sql -> bindParam(':email', $user_email, PDO::PARAM_STR);
$query_new_user_insert = $sql->execute();
密码解密:
$query = "SELECT *
FROM users
WHERE user_email = :email OR user_name = :username;";
$sql = $this->db_connection->prepare($query);
$sql -> bindParam(':username', $user_email, PDO::PARAM_STR);
$sql -> bindParam(':email', $user_email, PDO::PARAM_STR);
$sql -> execute();
$result_of_login_check = $sql->fetch(PDO::FETCH_OBJ);
// if this user exists
if ($result_of_login_check->user_id != null) {
// get result row (as an object)
$result_row = $sql->fetch(PDO::FETCH_OBJ);
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if (password_verify($_POST['user_password'], $result_row[2])) {
// write user data into PHP SESSION
$_SESSION['user_id'] = $result_row[0];
$_SESSION['user_name'] = $result_row[1];
$_SESSION['user_email'] = $result_row[3];
$_SESSION['user_login_status'] = 1;
$_SESSION['success'] = 0;
非常感谢任何帮助! 谢谢!
答案 0 :(得分:1)
<?php
// if this user exists
if ($rst = $sql->fetch(PDO::FETCH_OBJ) != null) {
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if (password_verify($_POST['user_password'], $rst->user_password_hash) {
// write user data into PHP SESSION
$_SESSION['user_id'] = $rst->user_id;
$_SESSION['user_name'] = $rst->user_name;
$_SESSION['user_email'] = $rst->email;
$_SESSION['user_login_status'] = 1;
$_SESSION['success'] = 0;
}
}
?>
但是,在执行password_verify()函数之前,我会执行更多检查,因为它会导致性能损失。像Captcha或添加最大尝试,然后调用超时一分钟。