我正在做一个使用CakePHP 2.8构建的项目。在登录时,我将FLAG设置为1,在注销时将FLAG设置为0,这样帐户就可以一次在一台计算机上登录。
我面临的问题是在会话超时。我感到困惑的是,如何在会话超时时将数据库中的标志设置为0。有没有办法在会话超时时运行更新查询?
我正在使用CORE配置文件设置SESSION超时限制,如下所示:
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 30, // The session will timeout after 30 minutes of inactivity
'cookieTimeout' => 1440, // The session cookie will live for at most 24 hours, this does not effect session timeouts
'checkAgent' => false,
'autoRegenerate' => true, // causes the session expiration time to reset on each page load
));
这是logout函数
public function logout() {
$id = $this->Auth->User('id');
$this->User->updateAll(array('WebLoggedIn'=>0), array('User.id'=>$id));
$this->Auth->logout();
// redirect to the home
return $this->redirect('/');
}
不行
问题中的想法是行不通的。与会话相关的移动部分,在问题中的配置是:
- 存储在服务器上的文件,其中包含序列化的会话数据,每次将会话写入 时,该文件都会更新
- 一个标准的php cron作业,它删除已经过期的会话文件(参见
/etc/cron.d/php5
或同等) - 一个浏览器cookie,将用户的浏览器会话链接到服务器上的文件
当用户的会话超时时,这意味着他们提供的会话id不对应于服务器上的文件,或者他们根本没有提供会话cookie。没有&嘿,这个会话已经过期"事件,并且不能保证用户会提供旧的会话id供您检查它是否有效。
工作方案
一个简单的(这也意味着naïve和可能容易绕过)解决方案是不存储一个布尔值,而是存储他们的会话将在数据库中过期的时间。例如,有类似这样的代码:
// App Controller
public function beforeFilter()
{
$userId = $this->Auth->user('id');
if ($userId) {
$this->User->updateAll(
array('active_session_expires'=> time() + (30 * 60)),
array('User.id'=>$id)
);
}
}
在用户控制器中:
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
if ($this->Auth->user('active_session_expires') > time()) {
$this->Flash->error('You are still logged in somewhere else');
return $this->logout();
}
$this->User->updateAll(
array('active_session_expires'=> time() + (30 * 60)),
array('User.id'=> $this->Auth->user('id'))
);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout()
{
$id = $this->Auth->User('id');
if ($id) {
$this->User->updateAll(
array('active_session_expires'=> time()),
array('User.id'=>$id)
);
$this->Auth->logout();
}
return $this->redirect('/');
}
。每次他们做某事时,更新数据库以跟踪他们的活动。如果他们试图在现有会话到期之前登录-立即注销他们。期望需要测试/修改这个示例代码,它提供给你一个想法,不一定是一个完整的和工作的解决方案。
这与您已经链接到的答案相似。