TL;DR
This guide shows you how to set cookies in CakePHP using the Response object, ensuring they are correctly sent as response headers. We’ll cover basic cookie setting and options like expiry dates and paths.
Setting a Basic Cookie
- Access the Response Object: In your controller action, get an instance of the
Responseobject. - Use the
setCookie()Method: Call thesetCookie()method on the response object to create a cookie.
Example:
$this->response = $this->response->withCookie('my_cookie', 'cookie_value');
Setting Cookie Options
You can control various aspects of the cookie using an array of options as the third argument to setCookie().
- Expiry Date: Set how long the cookie should last.
- Path: Define which paths on your website the cookie is valid for.
- Domain: Specify the domain the cookie applies to.
- Secure: Ensure the cookie is only sent over HTTPS connections.
- HttpOnly: Prevent client-side JavaScript from accessing the cookie (for security).
Example with options:
$options = [
'expires' => '+1 week',
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httpOnly' => true
];
$this->response = $this->response->withCookie('my_cookie', 'cookie_value', $options);
Deleting a Cookie
- Set Expiry Date to the Past: To delete a cookie, set its expiry date to a time in the past.
Example:
$options = [
'expires' => '-1 day',
'path' => '/', // Must match original path!
'domain' => 'example.com', //Must match original domain!
];
$this->response = $this->response->withCookie('my_cookie', '', $options);
Checking if a Cookie is Set
- Use
request()->cookie(): Check for the cookie’s existence in the request object.
Example:
if ($this->request->cookie('my_cookie')) {
echo 'Cookie is set!';
} else {
echo 'Cookie is not set.';
}
Important Considerations
- Path and Domain: Ensure the
pathanddomainoptions when deleting a cookie match those used when setting it. - Security: Always use the
secureoption for sensitive cookies to protect them during transmission. - HttpOnly: Enable
httpOnlyto prevent cross-site scripting (XSS) attacks from accessing your cookies.

