密码正确时显示PHP登录验证消息



我已经使用PHP为我的网站创建了一个登录页面。对于验证,如果用户名不存在、密码错误或用户没有输入其中一个或另一个,我希望显示错误消息。除了验证密码是否正确之外,我的大多数验证都有效。我使用的代码如下。我认为问题出在password_verify-if语句上。即使密码正确,也会出现提示用户密码不正确的错误消息。

<?php
// Initalise session
session_start();
//Check if the user is already logged in, if yes then redirect to members page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: members.php");
exit;
}
//Include config file
require_once "config.php";
//Define variables and initalise with empty values
$username = $password = "";
$username_err = $password_err = "";
//Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter your username.";
} else{
$username = trim($_POST["username"]);
}
//Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
//Validate credentials
if(empty($username_err) && empty($password_err)){
//Prepare a select statement
$sql = "SELECT username, password FROM users WHERE username = ?";
if($stmt = $mysqli->prepare($sql)){
//Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $param_username);
//Set parameters
$param_username = $username;
//Attempt to execute the prepared statement
if($stmt->execute()){
//Store result
$stmt->store_result();
//Check if username exists, if yes then verify password
if($stmt->num_rows == 1){
//Bind result variables
$stmt->bind_result($username, $password);
if($stmt->fetch()){
if(password_verify($password, $_POST['password'])){
//Password is correct, so start a new session
session_start();
//Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
//Redirect user to members page
header("location: members.php");
} else {
//Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
//Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
//Close statement
$stmt->close();
}
}
//Close connection
$mysqli->close();
}
?>

您的变量被翻转:

if(password_verify($password, $_POST['password'])){

应该是

if(password_verify($_POST['password'], $password)){

注意事项

在散列之前,没有必要对密码进行转义或使用任何其他清理机制。这样做会更改密码,并导致不必要的额外编码。

PHP中的密码哈希至少有60个字符长,请确保存储密码的列较大,以便处理未来的哈希算法。CCD_ 1或CCD_。

相关内容

  • 没有找到相关文章

最新更新