好的,作为我教育的一个副项目,我目前正在使用 PHP 和 mysqli 开发一个安全的登录系统。一直很顺利,但现在我遇到了一个让我和我的同龄人、老师和我都感到困惑的问题。
我正在通过 password_hash 和 password_verify 散列和检查我的密码。
当我创建一个帐户时,所有内容都会正确存储在数据库中。然后,当我尝试使用正确的密码登录时,它给了我一个错误,我的密码不正确。
现在这是踢球者:当我进入 PHPMyAdmin 时,复制存储在数据库中的散列密码,并使用该精确复制的密码更新密码字段......它有效。我可以使用我使用的密码按预期登录,它不会给我任何错误。
有谁知道发生了什么,以及如何解决它?
用于注册的代码:
public function createAccount()
{
global $con;
$this->password = password_hash($this->password, PASSWORD_DEFAULT)."\n";
$sql='INSERT into user (username, password, email, creation_date)
VALUES (?,?,?,?)';
// Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
}
// Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('ssss',$this->username,$this->password,$this->email,$this->creationDate);
// Execute statement
$stmt->execute();
echo $stmt->insert_id;
echo $stmt->affected_rows;
$stmt->close();
$_SESSION['login'] = true;
$_SESSION['username'] = $username;
Header("Location: index.php");
}
用于验证凭据的代码:
public function fetchCredentials() {
// Select a set of credentials from the username given in form and return as array
global $con;
$sql = 'SELECT id, password FROM user WHERE username = ?';
// Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
}
// Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s',$this->username);
// Execute statement
$stmt->execute();
// Store all results in an array
$rs=$stmt->get_result();
$arr = $rs->fetch_all(MYSQLI_ASSOC);
$stmt->close();
return($arr);
}
public function validateCredentials() {
// Get credentials
$arr = $this->fetchCredentials();
// Validate username
if (count($arr) > 1) {
$this->error = 'crit';
$this->abort = true;
} else if (count($arr) < 1) {
$this->error = 'badLogin';
$this->abort = true;
} else {
$arr = $arr[0];
}
echo $arr['password'].'<br>'.$this->password;
// Validate password. NOTE: This is where the issue arises. Password_verify() will return false where it should return true.
if ($this->abort == false && !password_verify($this->password, $arr['password'])) {
$this->error = 'badLogin';
$this->abort = true;
}
// Return values if needed
if ($this->abort == false) {
$this->id = $arr['id'];
}
return $this->abort;
}
调用登录的部分:(是的,validatecredentials 函数被调用了两次。是的,还有一些其他的东西写得不是很好。这部分代码仍然需要一些工作,这是第一件事我会在解决上述问题后做)
function login()
{
$newCred = new credentials(
$_POST['username'],
$_POST['password']);
if ($newCred->checkForm() == false
&& $newCred->validateCredentials() == false) {
$newLogin = new login(
$newCred->validateCredentials()['id']);
$newLogin->login();
$newLogin->getUserDetails();
} else {
$newCred->fetchError();
}
}