Cookies

A cookie is a small value the browser stores and sends back on later requests. Use it for a preference such as compact view. The Sessions example stores that preference on the server. Here the browser stores the preference itself, so treat it as input and accept only the values your application recognizes.

Reading Cookies

Use Request::cookies() to read cookies from the current request. This example accepts compact and falls back to comfortable for a missing or unexpected value.

$view = $request->cookies()->string("view", "comfortable");
$view = $view === "compact" ? "compact" : "comfortable";

Setting Cookies on a Response

Create a cookie with Cookie::create() and attach it to the response you return. expiresAfter() takes seconds. The path / makes the cookie available across the site.

use Atom\Http\Cookie;

$cookie = Cookie::create("view", "compact")
    ->withPath("/")
    ->expiresAfter(7 * 86400)
    ->withSameSite("Lax")
    ->withHttpOnly();

return $response->cookie($cookie);

Use withSecure() when the cookie should travel only over HTTPS. The browser applies the cookie from the response's Set-Cookie header and sends it on matching later requests.

Expire the cookie using the same name, path, and domain you used to set it. After the browser applies the response, the next read falls back to comfortable.

return $response->removeCookie("view", path: "/");

Cookies from Services

When a service sets the preference and another part of the application returns the response, inject Atom\Http\CookieJar. Queue the cookie on the jar and Atom applies it to the final response, including redirects.

$cookies->set($cookie);