我在测试项目中使用cookie时遇到问题,我正在尝试实现remember_me功能,如果用户在登录时单击了“记住我”按钮并在自动注销时保持用户登录30天如果在登录期间未单击按钮,浏览器将关闭。目前我正在做(connect.php文件):问题是,无论他是否点击了“记住我”按钮,它目前都会让用户隐藏起来
<?php
ini_set('session.cookie_lifetime', 3600 * 24 * 30);
session_start();
//Our MySQL user account.
define('MYSQL_USER', 'root');
//Our MySQL password.
define('MYSQL_PASSWORD', '');
//The server that MySQL is located on.
define('MYSQL_HOST', 'localhost');
//The name of our database.
define('MYSQL_DATABASE', 'qh_beer_shop');
/**
* PDO options / configuration details.
* I'm going to set the error mode to "Exceptions".
* I'm also going to turn off emulated prepared statements.
*/
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
/**
* Connect to MySQL and instantiate the PDO object.
*/
$pdo = new PDO(
"mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
MYSQL_USER, //Username
MYSQL_PASSWORD, //Password
$pdoOptions //Options
);
$pdo->query('SET NAMES utf8');
登录:
<?php
require_once 'connect.php';
if(isset($_SESSION['user'])) {
header('Location: login.php');
exit;
}
$error = '';
try {
//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//Retrieve the field values from our registration form.
// $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
// $password = !empty($_POST['password']) ? trim($_POST['password']) : null;
//Construct the SQL statement and prepare it.
$sql = "SELECT
id AS id,
username AS username,
password AS password,
email AS email,
phone AS phone,
address AS address,
first_name AS first_name,
last_name AS last_name,
age AS age
FROM
users
WHERE
username = ?
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$passwordHash = $user['password'];
if (!password_verify($password, $passwordHash)) {
setcookie('remember_me', '', time() - 100000);
throw new Exception("Wrong username or password!");
}
$hour = time() + 3600;
setcookie('ID_my_site', $_POST['username'], $hour);
if($_POST['remember']) {
$month = time() + 3600 * 24 * 30;
setcookie('remember_me', $_POST['username'], $month);
}
elseif(!$_POST['remember']) {
if(isset($_COOKIE['remember_me'])) {
$past = time() - 100;
setcookie('remember_me', '', $past);
}
}
$_SESSION['id'] = $user['id'];
$_SESSION['user'] = $user['username'];
header('Location: profile.php');
}
} catch (Exception $exception) {
$error = $exception->getMessage();
}
&GT;