Reading and Writing Cookies in CakePHP 4

Reading and Writing Cookies in CakePHP 4

This example shows you how to check if a cookie (guestCookie) is available from the browser, and if not, that cookie is set.

//check for existing session cookie
$guestID = $this->request->getCookie('guestCookie');
if(!$guestID) {
    $guestID = uniqid('', true);
    
    $cookie = Cookie::create('guestCookie', $guestID, [
        'expires' => date("Y-m-d H:i:s", strtotime("+1 hour")),
        'http' => true,
    ]);
    $this->response = $this->response->withCookie($cookie);
} else {
    debug($guestID);exit;
}

Additional Resources:

Share this Post