EssEss
EssEss

Reputation: 73

CakePHP 3.5 Writing and Reading Cookie

First of all, I've tried these two solutions provided in these two links

How to set and get Cookies in Cakephp 3.5

How to create cookies at controller level in CakePHP 3.5?

But, it just doesn't work somehow. I've provided an example of how I tried to write and read cookie. But none of them work.

Write Cookie

use Cake\Http\Cookie\CookieCollection;
use Cake\Http\Cookie\Cookie;

public function writeCookie() {
        $cookie = new Cookie(
            'remember_me', // name
            1, // value
            (Time::now())->modify('+1 year'), // expiration time, if applicable
            '/', // path, if applicable
            '', // domain, if applicable
            false, // secure only?
            true // http only ?
        );
        $cookies = new CookieCollection([$cookie]);//To create new collection
        $cookies = $cookies->add($cookie);//to add in existing collection

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

Read Cookie

public function readCookie(){
       $cookie = $this->request->getCookie('remember_me');
       debug($cookie); //is getting a null value
}

Could somebody point me to the correct direction to write and read cookie in CakePHP 3.5?

Upvotes: 0

Views: 876

Answers (1)

Ramkumar
Ramkumar

Reputation: 21

The Problem is you are write the cookie in wrong way. You should write the $cookie after add to the Cookie collection. check the below code.

Write Cookie

    $cookie = new Cookie('remember_me', 
        1, 
        (Time::now())->modify('+1 year'),
        '/', // path, if applicable
        '', // domain, if applicable
        false, // secure only?
        true // http only ?
    );
    $cookies = new CookieCollection([$cookie]);
    $this->response = $this->response->withCookie($cookie);

Upvotes: 0

Related Questions