Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create cookies at controller level in CakePHP 3.5?

I have problems to get cookies to work in cakephp 3.5.x.

in earlier versions I've used the Cookie component but this is now deprecated. Its unclear for me how to use this new middlewarestuff for reading and writing cookies.

The documentation is unclear for me. It shows me how to set up the cookie middleware but not how to handle creating cookies in a controller. Is there anyone who has handled cookies in 3.5.x?

like image 554
virido Avatar asked Dec 07 '25 18:12

virido


1 Answers

The middleware only replaces the encryption part of the Cookie component (which basically is the only thing it did as of CakePHP 3.0 anyways), if required it automatically encrypts and decrypts the cookies that you've configured.

You do not use the middleware to read or write cookies, that is done via the request and response objects, which is the default since CakePHP 3.

Reading and writing cookies from within a controller action can be as simple as:

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

See also

  • Cookbook > Controllers > Request & Response Objects > Request > Cookies
  • Cookbook > Controllers > Request & Response Objects > Response > Setting Cookies
  • Cookbook > Controllers > Request & Response Objects > Cookie Collections
like image 113
ndm Avatar answered Dec 10 '25 12:12

ndm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!