我的问题是,当我尝试使用正确的密码登录时,它仍会显示错误消息“您输入了错误的密码,请重试!”。(注册工作正常,检查用户是否已存在的部分工作正常)这是代码:
register.php (works):
<?php
include('db_conn.php'); //db connection
session_start();
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
$_SESSION['email'] = $_POST['email'];
$_SESSION['full_name'] = $_POST['name'];
// Escape all $_POST variables to protect against SQL injections
$full_name = $mysqli->escape_string($_POST['name']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$usertype = $mysqli->escape_string("A");
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'") or die($mysqli->error());
if (isset($_POST["submit"])){
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
// header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
$sql = "INSERT INTO user (Email, Password, UserType, FullName, Hash) "
. "VALUES ('$email','$password', '$usertype','$full_name', '$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"You are registered";
header("location: home.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
// header("location: error.php");
}
}
}
?>
sign_in.php (not working properly):
<?php
include('db_conn.php'); //db connection
session_start();
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'");
if (isset($_POST["submit"])){
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
// header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
echo $_POST['password'].$user['Password'];
if ( password_verify($_POST['password'], $user['Password']) ) {
$_SESSION['email'] = $user['Email'];
$_SESSION['full_name'] = $user['Name'];
$_SESSION['user_type'] = $user['UserType'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: home.php");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
// header("location: error.php");
}
}
}
?>
答案 0 :(得分:1)
不要转义密码哈希,直接输入DB是安全的:
$mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
为:
password_hash($_POST['password'], PASSWORD_BCRYPT);