psanjib
psanjib

Reputation: 1299

How to set cookie in cakephp

I want to set cookie but unable to set i have also used this public $components = array('Cookie');

i used in UsersController $this->Cookie->write('name', 'Larry'); echo on another controller echo $this->Cookie->read('name');

but there is no result

please suggest how to set cookie in cake php

thank Sanjib

Upvotes: 0

Views: 9684

Answers (4)

Axel Köhler
Axel Köhler

Reputation: 995

For people using CakePHP 4.x: Instead of using the cookie component, you now need to set a cookie to the Response object and fetch it via the Request object:

// Create cookie and set it to the Response object
$cookie = (new Cookie('name'))
    ->withValue('Larry');
$this->setResponse($this->getResponse()->withCookie($testCookie));
// Fetch a cookie's value from the Request object
$name = $this->getRequest()->getCookie('name'); // 'Larry'

Note that setting cookies will not work when using debug() or other output (e.g. echo), as headers cannot be sent if any output is already sent. You should get a warning about this as well.

For more information see this answer, or check the documentation on setting cookies and getting cookies .

Upvotes: 1

soulivong
soulivong

Reputation: 139

In your AppController src\Controller\AppController.php

put var $components = array('Cookie');

or you can set and retrieve cookie using original PHP.

Upvotes: 0

Zaphod Beeblebrox
Zaphod Beeblebrox

Reputation: 562

If you comment out

$this->Cookie->type('aes');

you should find the problem gone.

Upvotes: 0

Max Langerak
Max Langerak

Reputation: 1207

It looks as if you used this tutorial for cookies: http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html

What you probably missed is setting up the cookieComponent, this of course is necessary in order for you to use cookies.

public $components = array('Cookie');

public function beforeFilter() {
    parent::beforeFilter();
    $this->Cookie->name = 'baker_id';
    $this->Cookie->time = 3600;  // or '1 hour'
    $this->Cookie->path = '/bakers/preferences/';
    $this->Cookie->domain = 'example.com';
    $this->Cookie->secure = true;  // i.e. only sent if using secure HTTPS
    $this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
    $this->Cookie->httpOnly = true;
    $this->Cookie->type('aes');
}

Upvotes: 2

Related Questions