问题
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