How to set and get Cookies in Cakephp 3.5

白昼怎懂夜的黑 提交于 2019-12-13 03:59:53

问题


I have read the Cakephp documentation but it doesn't working well. Here is my code,

$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:


Please look at the documentation. You will find it in the following link:

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

To create a 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 ? );

Now add the cookie in the cookie collection:

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

Now read cookie this way.

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

Hope you will find it's working.

Here should mention an important point: Cookie writing and reading must be two separate http request.



来源:https://stackoverflow.com/questions/49772842/how-to-set-and-get-cookies-in-cakephp-3-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!