好吧,作为我教育的一个辅助项目,我目前正在使用PHP和mysqli开发一个安全的登录系统。事情进展顺利,但现在我遇到了一个问题,我的同龄人、老师和我都对此感到困惑
我正在通过password_hash和password_verify散列和检查我的密码。
当我创建一个帐户时,所有内容都会正确地存储在数据库中。然后,当我尝试使用正确的密码登录时,它会给我一个错误,即我的密码不正确。
现在关键是:当我进入PHPMyAdmin时,复制存储在数据库中的散列密码,并用该excact复制的密码更新密码字段。。。它是有效的。我可以使用我使用的密码按预期登录,它不会给我任何错误。
有人知道发生了什么事,以及如何解决吗?
用于注册的代码:
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();
}
}
好的,感谢所有提供帮助的人:谢谢。我刚刚得到同学的帮助,他设法找到了问题所在。我现在正在打自己。
$this->password = password_hash($this->password, PASSWORD_DEFAULT)."'n";
给你。"''n"。换行符。我从一个例子中获取了我的代码,出于某种原因,它就在那里。当我更新数据库时,换行符被删除了。