【发布时间】:2016-07-06 14:10:29
【问题描述】:
我正在尝试使用 phpmysql 使用密码散列。问题是 password_verify 到目前为止似乎对我不起作用。比如说,我注册时的密码是“123456789”。我使用
将它存储在数据库中 password_hash('123456789', PASSWORD_BCRYPT, array('cost' => 12));
然后当我在登录字段中输入“123456789”时,它什么也不做,失败了。
这是我的代码:
<?php
session_start();
include('db.php');
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p/>
<?php
if(isset($_POST['login']) && $_POST['login'] == 'Login') {
$loginEmail = $_POST['loginEmail'];
$loginPassword = $_POST['loginPassword'];
$sqlLogin = $db->prepare("SELECT * FROM registered_users WHERE email = ?");
$sqlLogin->bind_param("s",$loginEmail);
$sqlLogin->execute();
$sqlLogin = $sqlLogin->get_result();
$numrowsLogin = $sqlLogin->num_rows;
if($numrowsLogin == 1) {
$rowLogin = $sqlLogin->fetch_assoc();
$stored_password = $rowLogin['password'];
}
if(password_verify($loginPassword, $stored_password)){
header('Location: homepage.php');
}else{
echo 'invalid login';
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<table style="width:500px">
<tr>
<td width="30%"><input style="width: 200px; height: 25px; border-radius: 5px;" type="text" name="loginEmail" placeholder = "Email" required/><br/></td>
</tr>
<tr>
<td width="30%"><input style="width: 200px; height: 25px; border-radius: 5px;" type="password" name="loginPassword" placeholder = "Password" required/><br/></td>
</tr>
</table>
<input style="font-weight: bold; width: 70px; height: 25px; border-radius: 5px;" type="submit" name="login" value="Login"/>
</form>
</body>
</html>
【问题讨论】:
-
是否进行了任何基本调试,例如检查您的查询是否成功并返回存储的哈希?请注意,在表单的
action中使用$_SERVER['PHP_SELF']很容易受到 XSS 攻击。 -
您需要在任何
header('location: ...');-call 之后添加exit;,因为此时我们要停止向浏览器输出内容。 -
是的,抱歉,已更新
-
php.net/manual/en/function.password-hash.php
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a的示例为 60 个字符。你的密码栏和密码栏的长度是多少?不到60?如果是这样,那就是问题所在。太短了,你的代码会因为它默默地失败,你需要在改变列的长度后重新开始一个新的哈希。 @BishwaroopChakraborty -
请阅读@fred 的答案中的 cmets。你再也不会遇到这个问题了。
标签: php mysql password-hash php-password-hash