我正在尝试使用password_hash
和password_verify
在PHP中设置密码。我正在哈希密码,因为它正在进入数据库哈希,但是当我尝试在登录时取消密码时,它似乎不想工作。密码正在从Android应用程序收到,但在回显用户名和密码后,它们的正确性应该是正确的。要散列密码,我使用PASSWORD_DEFAULT
作为散列技术。
代码:
<?php
error_reporting(0);
require_once('dbconnect.php');
$username = $_POST["username"];
$password = $_POST["password"];
$result = $conn->query("SELECT * FROM User WHERE username ='$username'");
if(empty($result)){
die("Username doesn't exist");
}
$dbpass = $conn->query("SELECT password FROM User WHERE username = '$username'");
if (password_verify($password, $dbpass)){
$stmt = "SELECT * FROM User WHERE username='$username' and password='$password'";
$check = mysqli_fetch_array(mysqli_query($conn, $stmt));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}
else {
echo "password not unhashing";
}
$conn->close();
我错过了一些明显的东西吗?
答案 0 :(得分:2)
首先,使用预准备语句来消除SQL注入的威胁,或者您的登录屏幕成为攻击媒介。然后问题是你没有得到实际的dbpass,你得到一个包含$ dbpass的结果集,而没有取消引用它。
以这种方式尝试:
//username in where clause is coming from the user, don't execute it
//also fetch a clean copy of the username from the database we can trust to do things with like display -- assuming we filtered it on the way into the database.
$stmnt = $conn->prepare('select username,password from user where username = ?') or die('...');
//username must be a string, and to keep it clear it came from a user, and we don't trust it, leave it in POST.
$stmnt->bind_param('s',$_POST['username']) or die('...');
//Do the query.
$stmnt->execute() or die('...');
//Where to put the results.
$stmnt->bind_result($username,$dbpass);
//Fetch the results
if($stmnt->fetch()) //get the result of the query.
{
if(password_verify($_POST['password'],$dbpass))
{
//The password matches.
}
else
{
//password doesn't match.
}
}
else
{
//username is wrong.
}