我的注册脚本接受用户的密码,然后使用 PHP 的 password_hash 函数对密码进行加密,然后将其放入数据库中。当我使用刚刚创建的用户登录时,我收到检查密码是否相同的错误。就我而言,他们不是。当我在登录脚本中调用 password_verify 函数时,我做错了什么?
登记
if($_SERVER["REQUEST_METHOD"] == "POST"){
function secure($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return($data);
}
$p_num = secure($_POST["p_number"]);
$first_name = secure($_POST["first_name"]);
$last_name = secure($_POST["last_name"]);
$email = secure($_POST["email"]);
$password = secure($_POST["pw"]);
$verify_password = secure($_POST["pw_verify"]);
$program = secure($_POST["program"]);
$role = secure($_POST["role"]);
$logged_in = 0;
$registered = 0;
$image = "../images/profile_placeholder.png";
if($password != $verify_password){
echo "Nope. Passwords";
}
else{
$registered = 1;
$password = password_hash($password, PASSWORD_DEFAULT);
$insert = "INSERT INTO `$user_table`(`user_id`, `first_name`, `last_name`, `password`, `image`, `email`, `program`, `role`, `logged_in`, `registered`) VALUES('" .$p_num ."', '" .$first_name ."', '" .$last_name ."', '" .$password ."', '" .$image ."', '" .$email ."', '" .$program ."', '" .$role ."', '" .$logged_in ."', '" .$registered ."')";
$query = mysqli_query($connect, $insert);
echo "Success!";
}
}
登录
if($_SERVER["REQUEST_METHOD"] == "POST"){
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM `$user_table` WHERE `user_id` = '$p_num'";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$user_id = "{$row['user_id']}";
$first_name = "{$row['first_name']}";
$last_name = "{$row['last_name']}";
$user_name = $first_name ." " .$last_name;
$password = "{$row['password']}";
$image = "{$row['image']}";
$email = "{$row['email']}";
$program = "{$row['program']}";
$role = "{$row['role']}";
$status = "{$row['logged_in']}";
$registered = "{$row['registered']}";
if(($user_id == $p_num) && (password_verify($pwd, $password))){
$_SESSION["id"] = $user_id;
$_SESSION["user"] = $user_name;
$_SESSION["program"] = $program;
$_SESSION["pass"] = $password;
$_SESSION["image"] = $image;
$_SESSION["email"] = $email;
$_SESSION["role"] = $role;
$_SESSION["status"] = $status;
$_SESSION["registered"] = $registered;
$loggedin = "UPDATE `$user_table` SET `logged_in` = 1 WHERE `user_id` = '$user_id'";
}
var_dump($pwd);
var_dump($password);
}
这是我执行 var_dump 时得到的结果:
string(1) "1" string(16) "$2y$10$0aysCso3b"
很明显,密码没有匹配在一起。因此,在注册脚本上,密码被散列并发送到数据库。然后,当用户登录时,登录脚本会查看用户输入的登录密码,然后使用 password_verify 将其与数据库中的散列密码进行检查。然而,散列密码不接受未散列的密码作为匹配项。我不明白的是,为什么?