Jump to content
PrinceJ

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

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.

Share this post


Link to post
Share on other sites

??? You use the username and password value they provided, hash the password value and identify if they both match with those stored in database

Share this post


Link to post
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';
}

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...