登录我的网站时,您可以选择“记住我”。这将设置一个名为“R”的“记住我”cookie,其中包含用户标识和令牌。当会话cookie过期(设置为1天(86400秒))时,“记住我”cookie应该开始一个新会话。
当我测试它时,我将会话cookie的生命周期设置为60秒。在到期日期过后,“记住我”cookie开始一个新的会话。但是一个小时后,它将不会再开始新的会话,即使“记住我”cookie仍然存在,用户也必须再次登录。
令牌保存在数据库中。没有验证散列cookie的错误。找到了用户。
我在Stackoverflow上使用了以下指南:Keep me logged in
我的代码:
// Session class
private $_logged_in = false;
public $user_id;
public $userlevel;
function __construct() {
session_name('connected');
session_set_cookie_params(24*60*60);
ini_set('session.gc_maxlifetime',86400);
session_start();
}
public function is_logged_in() {
if(isset($_COOKIE['R'])) {
$this->check_cookie();
return $this->_logged_in;
} else {
$this->check_login();
return $this->_logged_in;
}
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->userlevel = $_SESSION['userlevel'];
$this->_logged_in = true;
} else {
unset($this->user_id);
unset($this->userlevel);
$this->_logged_in = false;
}
}
public function check_cookie() {
$cookie = $_COOKIE['R'];
list($user, $token, $mac) = explode(':', $cookie);
if($mac !== hash_hmac('sha256', $user . ':' . $token, SECRET_KEY)) {
$this->_logged_in = false;
}
if($user = User::find_by_id($user)) {
if($user->rememberme == $token) {
new Session();
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->userlevel = $_SESSION['userlevel'] = $user->userlevel_id;
$this->_logged_in = true;
}
}
}
public function login($user, $rememberme = "") {
if($user && $rememberme == "") {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->userlevel = $_SESSION['userlevel'] = $user->userlevel_id;
$this->_logged_in = true;
} elseif($user && $rememberme == 'rememberme') {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->userlevel = $_SESSION['userlevel'] = $user->userlevel_id;
if($user->setRememberMe($this->user_id)) {
$this->_logged_in = true;
}
}
}