在PDO中使用password_verify的正确方法是什么? [英] Whats the proper way to use password_verify with PDO?
问题描述
我似乎无法在我的php PDO代码中获得password_verify来工作.我的密码字段存储为varchar(255).我一直在阅读类似的问题,但是据我所知我已经正确设置了.我一定还是想念一些东西. 我的注册页面如下.
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.
我的登录页面如下.
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>";
登录页面的正文.
<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?
推荐答案
password_verify()
是(1)您要检查的未哈希密码和(2)您用作参考的哈希密码.在比较之前,您正在对第一个参数进行哈希处理:
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'])) {
您应该在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)?
这篇关于在PDO中使用password_verify的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!