Reputation: 47
I'm working on the login for my website. I use the password_hash()
function when creating the account, and store it in a MSSQL database as an nvarchar with 255 length. When I am trying to check the password given when a user is logging in, it never returns true. I've looked at some similar questions, but can't find anything that answers my problem.
Password encryption:
$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();
Password decryption:
$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;
Any assistance would be greatly appreciated! Thanks!
Upvotes: 0
Views: 891
Reputation: 7911
<?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;
}
}
?>
I would however perform more checks before you execute the password_verify() function cause its quite a performance hog. Like Captcha or add max attempts and then call a timeout for a minute.
Upvotes: 1