3

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?

ndm
  • 59,784
  • 9
  • 71
  • 110
virido
  • 41
  • 1
  • 2

2 Answers2

5

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

ndm
  • 59,784
  • 9
  • 71
  • 110
1

My case using Cake 3.8, just in case someone is lost as myself:

In your beforeFilter load the component

public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    //Load components, like Cookie
    $this->loadComponent('Cookie', ['expires' => '30 day']);
}

If cake complains:

Argument 1 passed to App\Controller\PController::beforeFilter() must be an instance of App\Controller\Event, instance of Cake\Event\Event given

Add the following to the top of your class:

use Cake\Event\Event;

And then reading and writing Cookies in your Controller action is breeze:

//Read
$fooVal = $this->Cookie->read('foo');
//Write
$this->Cookie->write('foo', 'bar');
Souvik Ghosh
  • 731
  • 8
  • 22