CakePHP 3.8-Cookie删除

时间:2019-09-26 09:12:20

标签: cakephp cookies settings cakephp-3.x

我试图为每个Cookie设置一个自动登录,但是无法使用CakePHP Books中显示的功能删除Cookie。

我有一个登录功能,用于检查“持久性”,即“记住我”复选框。 如果选中,则创建一个Cookie,生成一个密钥,将其分配给用户并随响应发送:

UsersController :: login()

if ($this->request->getData('persistence')) {
  $cookie = $this->Users->createLoginCookie($user, '+1 Month');

  $this->response = $this->response->withCookie($cookie
  );
}

return $this->redirect($this->Auth->redirectUrl());

UsersTable :: createLoginCookie();

public function createLoginCookie($user, $expiry){
  $key = Text::uuid();
  $user = $this->findByEmail($user['email'])->first();
  $user->persistence_key = $key;
  $this->save($user);

  $cookie = new Cookie(
    'persistence_key', $key,
    new DateTime($expiry),
    '',
    '',
    false,
    false
  );
   return $cookie;
}

如果用户手动注销,我希望删除Cookie:

UsersController :: logout()

if ($cookie = $this->request->getCookie('persistence_key')) {
  $this->response = $this->response->withExpiredCookie($cookie);
}
$this->Flash->success('You have been logged out.');
return $this->redirect($this->Auth->logout());

遗憾的是,该Cookie不会被删除。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您的代码$cookie = $this->request->getCookie('persistence_key')返回cookie值,而不是cookie本身。因此,您将cookie值而不是cookie名称传递给withExpiredCookie()方法。而且无论如何,现在不建议使用传递cookie的名称。

类似的事情应该起作用:

$cookie = new Cookie('persistence_key');
$this->response = $this->response->withExpiredCookie($cookie);

请注意,cookie路径还必须与您创建cookie的方式相对应。由于我在本地主机上有很多CakePHP应用程序,因此在创建cookie时,我倾向于指定cookie路径:

$cookie = new Cookie('my-cookie');
$cookie = $cookie->withPath(Router::url('/'));

所以我必须像这样破坏它们:

$cookie = new Cookie('my-cookie');
$cookie = $cookie->withPath(Router::url('/'));
$this->response = $this->response->withExpiredCookie($cookie);