Read & Write Cookies in CakePHP 3
Read & Write Cookies in CakePHP 3
The following example uses the Request & Response objects to save a cookie value.
Add these to your controller:
use Cake\Http\Cookie\Cookie; use DateTime;
Below, we check to see if the cookie_id cookie is empty, and set it to a unique id, using the response object.
$cookie_id = $this->request->getCookie('cookie_id');
if(is_null($cookie_id) || $cookie_id == '') {
$this->response = $this->response->withCookie('cookie_id', [
'value' => uniqid(),
'path' => '/',
'httpOnly' => true,
'secure' => false,
'expire' => strtotime('+1 year')
]);
}
Then, when we want to read the value, simply use the request object, like below:
$this->request->getCookie('cookie_id')
See also: https://book.cakephp.org/3/en/controllers/request-response.html#cookies