Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Sessions and cookies

HTTP does not remember earlier requests. For a site to recognise a visitor — keep a cart, the chosen language, the colour theme — sessions and cookies are used. A session keeps data on the server, a cookie in the browser.

Writing and reading the session

The session comes from the request:

#[Route('/visit', name: 'visit')]
public function visit(Request $request): Response
{
    $session = $request->getSession();
 
    $count = $session->get('visits', 0) + 1;
    $session->set('visits', $count);
 
    return new Response("You have been here $count times");
}

The second argument of get() is the value used when the key does not exist yet. The session starts by itself on first use.

Session methods

MethodWhat it does
get('key', $default)Reads a value
set('key', $value)Writes one
has('key')Checks that it exists
remove('key')Removes one value
clear()Removes everything

A cart

Arrays can be kept in the session:

#[Route('/cart/add/{id}', name: 'cart_add', methods: ['POST'])]
public function add(int $id, Request $request): Response
{
    $session = $request->getSession();
 
    $cart = $session->get('cart', []);
    $cart[$id] = ($cart[$id] ?? 0) + 1;
    $session->set('cart', $cart);
 
    return $this->redirectToRoute('cart');
}

The session in a template and in a service

<p>Items in the cart: {{ app.session.get('cart', [])|length }}</p>

A service has no request at hand — it takes the session through RequestStack:

use Symfony\Component\HttpFoundation\RequestStack;
 
class Cart
{
    public function __construct(private RequestStack $requestStack) {}
 
    public function items(): array
    {
        return $this->requestStack->getSession()->get('cart', []);
    }
}

A cookie is added to the response:

use Symfony\Component\HttpFoundation\Cookie;
 
#[Route('/theme/{name}', name: 'theme')]
public function theme(string $name): Response
{
    $response = $this->redirectToRoute('home');
 
    $response->headers->setCookie(
        Cookie::create('theme', $name, new \DateTime('+1 year'))
    );
 
    return $response;
}
$theme = $request->cookies->get('theme', 'light');
 
$response->headers->clearCookie('theme');

Which to choose

SessionCookie
Where it is keptOn the serverIn the browser
Can the visitor change itNoYes
LifetimeUntil the browser closes, or longer if configuredSet explicitly
Used forA cart, checkout stepsTheme, language

Common mistake

A visitor can read and forge a cookie. Do not keep a price, a role or a user identifier in one and then trust those values. Anything that affects rights or money is kept on the server — in the session or the database.

Thanks for reading!

Donate to the site — we work hard for you.