How to set and get Cookies in Cakephp 3.5

2.1k views Asked by At

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

There are 1 answers

0
Mushfiqur Rahman On BEST ANSWER

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.