craisondigital craisondigital - 1 month ago 15
MySQL Question

Whats the proper way to use password_verify with PDO?

I can't seem to get password_verify to work w/in my php PDO code. My pass field is stored as varchar(255). I've been reading similar questions, but from what I can tell I have it set up right. I must still be missing something.
My registration page is as follows..

$user = $_POST['username']
$pass = $_POST['pass'];
$passH = password_hash($pass, PASSWORD_DEFAULT);
$query = $con->prepare("INSERT INTO emps (user, pass) VALUES (?, ?)");
$query->execute([$user, $passH]);


An encrypted password is now successfully stored in my database.

My Login Page is as follows..

if(isset($_POST['login'])) {
$username = $_POST['username'];
$pass = trim($_POST['pass'];
$passH = password_hash($pass, PASSWORD_DEFAULT);
$sel_user = $con->prepare("SELECT id, username, pass, gid FROM emps WHERE gid!=4 AND username=?");
$sel_user->execute([$username]);
$check_user=$sel_user->fetch();
if(count($check_user)>0 && password_verify($passH, $check_user['pass'])) {
$_SESSION['username']=$check_user['username'];
header("Location: xadmin.php");
exit;
}
else {
echo "<script>alert('Not Found')</script>";


Body of Login Page..

<form action="login.php" method="post">
<table width="100%" border="0">
<tbody>
<tr>
<td bgcolor="#3B3B3B" height ="35" class="BodyTxtB" align="center">Administrator Login</td></tr>
<tr height="20"><td></td></tr>
<tr>
<td class="BodyTxtB" align="center">Username</td>
</tr>
<tr>
<td class="BodyTxtB" align="center"><input type="text" class="BodyTxtBC" name="username" required="required"/></td>
</tr>
<tr height="20"><td></td></tr>
<tr>
<td class="BodyTxtB" align="center">Password</td>
</tr>
<tr>
<td class="BodyTxtB" align="center"><input type="password" class="BodyTxtBC" name="pass" required="required"/></td>
</tr>
<tr height="20"><td></td></tr>
<tr height="35"><td align="center"><input type="image" src="images/btn_login.jpg" name="login" value="Login"/>
<input type="hidden" name="login" value="Login" /></td></tr>
<tr height="20"><td></td></tr>
</tbody>
</table>
</form>


Can anyone spot any errors?

Answer

The arguments for password_verify() are (1) the unhashed password you want to check and (2) the hashed password you are using as a reference. You are hashing the first argument before comparing:

$pass = trim($_POST['pass'];
$passH = password_hash($pass, PASSWORD_DEFAULT);
// ...
if(count($check_user)>0 && password_verify($passH, $check_user['pass'])) {

You should be doing password_verify($pass /** the unhashed one */, $check_user['pass'])

Also, trimming the password is a bad idea. What if the password actually includes whitespace (which you should allow it to do)?

Comments