Jump to content

How to use prepared statement for login when password is hashed and salted?


PrinceJ

Recommended Posts

Well, As the title says:

MySQL Database stores password of users using default PHP password_hash() function when registering.

Now I am not able to find out a way to login using prepared statement to avoid SQL injections,

I mean I can't use password_verify as I am not able to fetch user password from database without executing the query.

Link to comment
Share on other sites

The logic is pretty simple and can be done easily with prepared statements. There are many ways to do it, here is one of them:

<?php
$username = $_POST['username'];
$password = $_POST['password'];

// Database connection logic. See documentation:
// http://php.net/manual/en/pdo.construct.php
// $pdo = new PDO(...)

$query = $pdo->prepare('SELECT `hashed_password` FROM `users` WHERE `username` = :username LIMIT 1');
$query->bindParam(':username', $username);
$query->execute();
$query->bindColumn('hashed_password', $hashed_password);

if($query->fetch(PDO::FETCH_BOUND)) {
  if(password_verify($password, $hashed_password)) {
    echo 'User is logged in';
  } else {
    echo 'Wrong username or password';
  }
} else {
  echo 'Wrong username or password';
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...