登录数据库时,我在数据库上使用password_verify
时总是说密码不正确,而在数据库中,我使用char 255作为密码。
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$userrecord1 = mysqli_query($db, "SELECT * FROM users WHERE username='$_POST[username]' LIMIT 1");
if (count($userrecord1) == 1 ) {
$urow1 = mysqli_fetch_array($userrecord1);
$hash = $urow1["password"];
}
// attempt login if no errors on form
if (count($errors) == 0) {
$passuser = password_verify($password, $hash);
$query = "SELECT * FROM users WHERE (username='$username' OR email='$username') AND password='$passuser' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
答案 0 :(得分:0)
我想说明几件事,
global
关键字-您应该改为将值作为参数传递给函数。password_verify()
验证了密码,密码就正确了,并且用户已经验证了登录名。 if (count($userrecord1) == 1 ) {
并没有多大意义,因为您尚未提取任何记录。 exit;
通话后使用header("Location: ..");
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$stmt = $db->prepare("SELECT password, user_type FROM users WHERE username=? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($dbPassword, $userType);
if ($stmt->fetch() && password_verify($password, $dbPassword)) {
if ($userType == 'admin') {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
exit;
} else {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
exit;
}
} else {
$errors[] = "Wrong username/password combination";
}
}