如何在Cakephp 3.5中设置和获取Cookie

时间:2018-04-11 10:36:11

标签: cakephp-3.4

我已阅读Cakephp文档,但效果不佳。 这是我的代码,

$this->response = $this->response->withCookie('remember_me', [
    'value' => 'yes',
    'path' => '/',
    'httpOnly' => true,
    'secure' => false,
    'expire' => strtotime('+1 year')
]);
$rememberMe = $this->request->getCookie('remember_me');

1 个答案:

答案 0 :(得分:0)

请查看文档。您可以在以下链接中找到它:

https://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Http\Cookie\CookieCollection

创建cookie

use Cake\Http\Cookie\Cookie;

$cookie = new Cookie(
    'remember_me', // name
    1, // value
    new DateTime('+1 year'), // expiration time, if applicable
    '/', // path, if applicable
    'example.com', // domain, if applicable
    false, // secure only?
    true // http only ? );

现在在cookie集合中添加cookie:

use Cake\Http\Cookie\CookieCollection;
$cookies = new CookieCollection([$cookie]);//To create new collection
$cookies = $cookies->add($cookie);//to add in existing collection

现在以这种方式阅读cookie。

   $cookie = $cookies->get('remember_me');

希望你会发现它正在发挥作用。

这里应该提一个重点:Cookie的编写和阅读必须是两个单独的http请求。