我刚为登录表单添加了一个复选框。如果用户勾选该框,则应存储电子邮件和哈希密码。目前,它没有存储cookie。这也是我第一次设置cookie。
这是表单的复选框部分:
<input type="checkbox" class="remember-user cb" name="remember" value="yes" <?php if(isset($_COOKIE['cookemail']) && ($_COOKIE['cookpass'])) {echo 'checked="checked"';}else {echo '';}?>>Remember me
这是我的do-login.php&#39;的一部分。 (将在提交登录表单时调用):
$email = veilig($mysqli,$_POST['email']);
$password = safe($mysqli,$_POST['password']);
$remember = safe($mysqli,$_POST['remember']);
$stmt = $mysqli->prepare("SELECT user_id, password, salt FROM members WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt);
$stmt->fetch();
//Hashed password
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
//Check if the user exists
if ($stmt->num_rows == 1) {
//Check of the password is correct
if ($db_password == $hashedPW) {
//Cookie the input fields
$year = time() + 2592000; // 30 DAGEN
if($remember == "yes") {
setcookie('cookemail', $email, $year);
setcookie('cookpass', $password, $year);
}
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$email = preg_replace("/[^a-zA-Z0-9_\-]+/","", $email);
$_SESSION['email'] = $email;
echo "succesLogin";
} else {
echo "wrongPassword";
}
我错过了什么吗?
编辑:现在正在设置Cookie!将代码更改为:
if ($db_password == $hashedPW) {
//Set cookie when user has succesfully logged in
$year = time() + 2592000; // 30 DAGEN
//Random text
$secret_emword = "dinosaurs are way too cool for our universe";
$secret_pword = "i eat lots of jelly beans and i regret nothing";
if($remember == "yes") {
setcookie('Auth_', hash('sha256', $email . $secret_emword), $year);
setcookie('A_chkx2_', hash('sha256', $password . $secret_pword), $year);
//Make sessions
$_COOKIE['Auth_'] = preg_replace("/[^a-zA-Z0-9_\-]+/","", $_COOKIE['Auth_']);
$_SESSION['Auth_'] = $_COOKIE['Auth_'];
$_SESSION['A_chkx2_'] = $_COOKIE['A_chkx2_'];
}
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$email = preg_replace("/[^a-zA-Z0-9_\-]+/","", $email);
$_SESSION['email'] = $email;
echo "succesLogin";
} else {
echo "wrongPassword";
}
我目前面临的唯一问题是,在Cookie过期或签字之前,我不会保持登录状态。以下是我的login_check函数:
//Check if user has been logged in
function login_check($mysqli) {
if (isset($_COOKIE['Auth_'], $_COOKIE['A_chkx2_'])) {
return true;
} else if (isset($_SESSION['email'], $_SESSION['user_id'])) {
$email = $_SESSION['email'];
$user_id = $_SESSION['user_id'];
return true;
} else {
// Not signed in
return false;
}
}
有什么想法吗?