1

I have read the Cakephp documentation but it doesn't working well. Here is my code,

$this->response = $this->response->withCookie('remember_me', [
    'value' => 'yes',
    'path' => '/',
    'httpOnly' => true,
    'secure' => false,
    'expire' => strtotime('+1 year')
]);
$rememberMe = $this->request->getCookie('remember_me');
Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
Zahid
  • 470
  • 1
  • 3
  • 15
  • 1
    Are you trying to do these two lines of code one after the other? I don't think that will work. Typical usage is to set the cookie in a response to one request, and then you can get that cookie in *future* requests. – Greg Schmidt Apr 11 '18 at 14:12
  • I am trying and working in the same function one after another, but can't read another page and return NULL – Zahid Apr 12 '18 at 05:11
  • Not at all clear why you'd want to read from a cookie that was only just now set, when you have the data that was used to set it. Cookies are used to persist data from one page load to the next, not within a single page load. – Greg Schmidt Apr 12 '18 at 14:02

1 Answers1

1

Please look at the documentation. You will find it in the following link:

https://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Http\Cookie\CookieCollection

To create a cookie

use Cake\Http\Cookie\Cookie;

$cookie = new Cookie(
    'remember_me', // name
    1, // value
    new DateTime('+1 year'), // expiration time, if applicable
    '/', // path, if applicable
    'example.com', // domain, if applicable
    false, // secure only?
    true // http only ? );

Now add the cookie in the cookie collection:

use Cake\Http\Cookie\CookieCollection;
$cookies = new CookieCollection([$cookie]);//To create new collection
$cookies = $cookies->add($cookie);//to add in existing collection

Now read cookie this way.

   $cookie = $cookies->get('remember_me');

Hope you will find it's working.

Here should mention an important point: Cookie writing and reading must be two separate http request.

Mushfiqur Rahman
  • 306
  • 4
  • 18