首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CakePHP 3.8 - Cookie删除

问CakePHP 3.8 - Cookie删除
EN

Stack Overflow用户
提问于 2019-09-26 09:12:20
回答 1查看 233关注 0票数 0

我试图为每个Cookie设置一个autoLogin,但是不能删除CakePHP书籍中显示的函数Cookie。

我有一个登录函数,它检查“持久性”,这是“记住我”复选框。如果选中,则创建Cookie,生成密钥,将其分配给用户,并将其与响应一起发送:

UsersController::login()

代码语言:javascript
复制
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();

代码语言:javascript
复制
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()

代码语言:javascript
复制
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());

遗憾的是,饼干不会被移除。

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2019-09-27 07:17:57

代码$cookie = $this->request->getCookie('persistence_key')返回cookie值,而不是cookie本身。因此,将cookie值传递给withExpiredCookie()方法,而不是cookie名称。不管怎么说,传递cookie名称现在已经不受欢迎了。

像这样的事情应该有效:

代码语言:javascript
复制
$cookie = new Cookie('persistence_key');
$this->response = $this->response->withExpiredCookie($cookie);

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

代码语言:javascript
复制
$cookie = new Cookie('my-cookie');
$cookie = $cookie->withPath(Router::url('/'));

所以我必须这样摧毁他们:

代码语言:javascript
复制
$cookie = new Cookie('my-cookie');
$cookie = $cookie->withPath(Router::url('/'));
$this->response = $this->response->withExpiredCookie($cookie);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58113385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档