Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 62 ยท Routing and Controllers

Sessions and Flash Messages

Store data between requests with the Symfony session, show one-time flash messages after redirects, configure storage, and keep API routes stateless.

HTTP forgets everything between requests. The server answers one request, then has no memory of who you were. A session fixes that: the server keeps a small bag of data for each visitor and gives the browser a cookie containing only an identifier. On the next request, the cookie brings the identifier back, and the server finds the right bag.

Symfony wraps PHP's session handling in an object-oriented API from the HttpFoundation component. This lesson covers reading and writing session data, flash messages (notices that survive exactly one redirect), where the data is stored, and how to mark routes as stateless so a JSON API never creates sessions at all. You should be comfortable with the request object and responses and redirects first.

Getting the session

In a controller, you can type-hint SessionInterface as an argument, or call $request->getSession(). Services that are not controllers inject RequestStack and ask it for the current session.

PHP
// src/Controller/CartController.php (real Symfony, read-only)
namespace App\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Attribute\Route;

final class CartController
{
    #[Route('/cart/add/{id<\d+>}', name: 'cart_add', methods: ['POST'])]
    public function add(int $id, SessionInterface $session): RedirectResponse
    {
        $cart = $session->get('cart', []);
        $cart[$id] = ($cart[$id] ?? 0) + 1;
        $session->set('cart', $cart);

        return new RedirectResponse('/cart');
    }

    #[Route('/cart', name: 'cart_show')]
    public function show(SessionInterface $session): Response
    {
        $cart = $session->get('cart', []);

        return new Response(sprintf('You have %d distinct items.', count($cart)));
    }
}

The everyday methods are few:

Method What it does
get($name, $default = null) Reads an attribute, or the default
set($name, $value) Stores a value
has($name) Checks if an attribute exists
remove($name) Deletes one attribute and returns its old value
clear() Deletes all attributes
all() Returns every attribute as an array
invalidate() Destroys the session and starts a new one
migrate() Gives the session a new id but keeps the data

Values are serialized, so store simple data (scalars, arrays, small value objects). Do not put Doctrine entities or large objects in the session: they bloat every request and become stale. Store an id and reload the entity when needed.

Two of those methods are security tools. Call migrate() (the Security component does this for you) after a login so an attacker who planted a known session id before login cannot reuse it. Call invalidate() on logout to throw everything away.

The session starts lazily

Symfony does not start a session just because one is configured. The session starts on first use, and the Set-Cookie header is only sent if a session was actually started. A visitor who only reads a public page gets no session cookie. This matters for performance and for caching, because a response with a cookie usually cannot be cached by a shared cache.

sequenceDiagram
    participant B as Browser
    participant S as Symfony
    participant St as Session storage
    B->>S: GET /cart (no cookie)
    S->>S: controller calls session->set()
    S->>St: write new session data
    S-->>B: response + Set-Cookie: session id
    B->>S: GET /cart (cookie with id)
    S->>St: load data for that id
    S-->>B: response built from stored data

The cookie carries only an id; the data stays on the server and is loaded on every later request.

Flash messages

A flash message is a one-time notice, typically shown after a form submission: "Product saved." You store it in the session, redirect, and show it on the next page. After it has been read once, it is gone. That behaviour is what the Post/Redirect/Get pattern needs: you should redirect after a successful POST so that refreshing the page does not resubmit the form, but then the confirmation has to travel across the redirect.

In a controller that extends AbstractController, the shortcut is addFlash():

PHP
// src/Controller/ProductController.php (real Symfony, read-only)
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;

final class ProductController extends AbstractController
{
    public function save(): RedirectResponse
    {
        // ... store the product ...

        $this->addFlash('success', 'Product saved.');
        $this->addFlash('info', 'It will appear in the catalog tomorrow.');

        return $this->redirectToRoute('product_index');
    }
}

Flash messages are grouped by a type string of your choice (success, warning, error, notice). Reading them in Twig is one loop; the call to app.flashes() also removes them from the session:

TWIG
{# templates/base.html.twig (real Symfony, read-only) #}
{% for type, messages in app.flashes %}
    {% for message in messages %}
        <div class="alert alert-{{ type }}">{{ message }}</div>
    {% endfor %}
{% endfor %}

You can also ask for one type, app.flashes('success'). Outside controllers you reach the flash bag with $session->getFlashBag(), which is available when the session is a Session object.

Put the flash loop in your base layout once, and every page can display notices without extra code. See layouts and blocks.

Runnable stand-in: session and flash bag

The real session talks to PHP's session handlers and cookies, which a lesson sandbox cannot do. This stand-in keeps the same shape: an id cookie, a server-side store, attributes, and a flash bag that empties when it is read. Two "requests" run in a row, with a redirect in between.

PHP Attributes and flash messages across a redirect (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first GET after the redirect prints the flash message; the refresh does not, but the ordinary session attribute (last_product) is still there. That difference is the whole point of flash messages.

Where session data lives

By default Symfony uses PHP's native file-based session handler, so data lands in files on the server. That is fine for one machine, but breaks down when you run several servers behind a load balancer, because a request may land on a server that does not have your file. Common alternatives:

  • Database: PdoSessionHandler stores sessions in a table.
  • Redis or Memcached: very fast, shared between servers, the usual production choice.
  • Cookie-only sessions are not offered out of the box, because session data should not live in a browser.

You configure the handler in config/packages/framework.yaml:

YAML
# config/packages/framework.yaml (real Symfony, read-only)
framework:
    session:
        handler_id: '%env(REDIS_URL)%'
        cookie_secure: auto
        cookie_samesite: lax
        cookie_lifetime: 0
        gc_maxlifetime: 3600

cookie_secure: auto sends the cookie only over HTTPS when the request is HTTPS, cookie_samesite: lax blocks the cookie on most cross-site POSTs, and gc_maxlifetime controls how long idle sessions survive. Handler details differ per backend, so check the documentation for yours before deploying.

Stateless routes

An API that authenticates with tokens does not need sessions. Mark such routes as stateless, and Symfony tells caches that the response never depends on a session:

PHP
// real Symfony, read-only
#[Route('/api/status', name: 'api_status', stateless: true)]
public function status(): JsonResponse
{
    return new JsonResponse(['ok' => true]);
}

If code on a stateless route tries to use the session, Symfony reports it as an error in debug mode instead of silently creating a session that would make the response uncacheable. It is a very cheap way to catch accidental session use. To keep all routes of an API stateless, put the option on the controller class or a route group.

The next stand-in shows lazy start and why it matters: it counts how many sessions get created for a mix of requests when only some of them touch the session.

PHP Lazy session start and stateless routes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Only /cart creates a session. The home page and the stateless API route stay cookie-free, and the buggy /api/oops is caught immediately.

Common mistakes

  • Showing flash messages before a redirect. Flashes are consumed when read. If you render them on the same request that created them, they may be lost after the redirect.
  • Storing big or fragile data. Keep sessions small: ids and flags, not entities.
  • Forgetting migrate() on privilege changes. Login and logout flows should rotate or destroy the session id.
  • Using sessions for APIs. Prefer tokens and stateless: true.
  • Reading the session in a cached page. One session read can make a public page unshareable by CDNs. Load per-user bits with a separate request instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the browser store for a Symfony session?

    The cookie carries only an id. The server uses it to find the stored data.
  2. 2. Why use a flash message after a successful form POST?

    After a POST you redirect (Post/Redirect/Get). A flash message travels across the redirect once and is removed when it is displayed.
  3. 3. A public page never touches the session. What does Symfony send?

    The session only starts when used, and a cookie is only sent for started sessions.
  4. 4. What does stateless: true on a route do?

    It is a promise that the response does not depend on a session. Symfony flags code that breaks that promise in debug mode.
  5. 5. Why should you call migrate() after a login?

    A new id stops an attacker who knew the old id from taking over the authenticated session.

Summary

  • A session keeps per-visitor data on the server; the browser holds only an id cookie.
  • Use get, set, has, remove and clear for attributes, and keep stored values small.
  • Flash messages (addFlash() in a controller, app.flashes in Twig) are shown once after a redirect.
  • Sessions start lazily, so pages that never use them stay cookie-free and cacheable.
  • Configure shared storage (Redis, database) for several servers, and mark API routes stateless: true.

Next up: Twig Basics.