0

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?

EssEss
  • 73
  • 10
  • If doesn't look like you're actually setting the cookies in the response anywhere, as per [the manual](https://book.cakephp.org/3.0/en/controllers/request-response.html#setting-cookies). – Greg Schmidt Jun 01 '18 at 05:59
  • Hi Greg, even if I have set it using one the method provided in the link above. I still can't access the cookie using $this->request from other page. – EssEss Jun 01 '18 at 06:27
  • Then you need to do some debugging, beginning with inspecting the HTTP request and response in your browser (or whatever client you are using) to check whether the cookie headers are sent in the response, and whether the cookie is being sent with the next request. – ndm Jun 01 '18 at 08:02
  • 1
    Any chance you're generating some output before trying to set the cookie? That would cause it to send the headers before the cookie is added, and once the headers are sent, there's no looking back. – Greg Schmidt Jun 01 '18 at 18:08

1 Answers1

0

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);
Ramkumar
  • 23
  • 7