我一直在浏览PHP中的password_hash()
和password_verify()
方法,并且我一直在尝试将其包含在我的代码中。我似乎无法让它工作,我已经通过一系列谷歌搜索,甚至一些问题在这里,但他们似乎没有解决问题。
我在数据库中的列长度为255.当我尝试运行代码时,收到$loginerror
消息。这是我的代码块。请问我做错了什么。
$signin_email=$_POST['signin_email'];
$signin_password=$_POST['signin_password'];
if($valid){
require_once 'scripts/connect_to_mysql.php';
$sql = "SELECT First_name, Last_name,Password FROM customer WHERE Email=? AND Password=? LIMIT 1";
$stmt=$conn->prepare($sql);//preparing the statement
if(!$stmt){
echo "Unable to prepare: ".$conn->errno. " " .$conn->error;
}
//executing the statement
//$date=date('d m Y h:i:s');
if(!$stmt->bind_param('ss', $signin_email, $signin_password)){//bind parameters to sql statement. i=integer, s=string, b=blob, d=double
echo "Binding parameters failed: ".$stmt->errno. " " . $stmt->error;
}
if(!$stmt->execute()){//executing the statement
echo "Statement Execution failed: ". $stmt->error;
}
if(!$stmt->bind_result($dbfirstname,$dblastname,$dbpassword)){// used to bind variables to a prepared statement for result storage
echo "Unable to bind results to variables: ".$stmt->error;
}
$stmt->store_result();
//echo $stmt->num_rows;
echo $dbpassword;
if(password_verify($signin_password, $dbpassword)){
if($stmt->num_rows===1){//to check if username and password actually exists
while($row=$stmt->fetch()){
$user=$dbfirstname. " ". $dblastname;
echo $user;
}
/*$_SESSION['user']=$user;
header('location:logintest.php');
exit();*/
}
}
else{
//$error="Invalid Email address/Password. Please try again";
$loginerror= "Invalid Email address/Password. Please try again";
}
$stmt->close();//closing the prepared statement
$conn->close();//closing the connection
}
答案 0 :(得分:1)
问题不在于password_verify
,而在于您构建查询的方式:
`$sql ="SELECT First_name, Last_name,Password FROM customer WHERE Email=? AND Password=? LIMIT 1";
您将$signin_password
绑定到该查询,并且它不包含来自$_POST
的哈希值。
有两种解决方案:
1)从查询中删除AND Password=?
- 您将使用password_verify
检查密码
2)将$signin_password
更改为:
$signin_password=password_hash($_POST['signin_password']);
(但这种使用password_verify的方式有点无关紧要。
答案 1 :(得分:-1)
$signin_password=$_POST['signin_password'];
$hash = password_hash($dbpassword, PASSWORD_DEFAULT);
if (password_verify($signin_password, $hash))
{
echo 'Password is valid!';
}
else
{
echo 'Invalid password.';
}
试试这个:)更好的选择就是建立你自己的查询。