44Avoid Starting Sessions for Anonymous Users
55===========================================
66
7- Sessionsin Symfony applications are automatically started wheneverthey are necessary.
8- This includes writing in theuser's session, creating a flash message and logging
9- in users. In order to start the session, Symfony creates a cookie which will be
10- added to every user request .
7+ Sessions are automatically started wheneveryou read, write or even check for the
8+ existence of data in the session. This means that if you need to avoid creating
9+ a session cookie for some users, it can be difficult: you must * completely * avoid
10+ accessing the session .
1111
12- However, there are other scenarios when a session is started automatically and a
13- cookie will be created even for anonymous users. First, consider the following
14- template code commonly used to display flash messages :
12+ For example, one common problem in this situation involves checking for flash
13+ messages, which are stored in the session. The following code would guarantee
14+ that a session is * always * started :
1515
1616..code-block ::html+jinja
1717
@@ -22,33 +22,17 @@ template code commonly used to display flash messages:
2222 {% endfor %}
2323
2424Even if the user is not logged in and even if you haven't created any flash message,
25- just calling the ``get() `` method of the ``flashbag `` will start a session. This
26- may hurt your application performance because all users will receive a session
27- cookie. To avoid this behavior, add a check before trying to access the flash messages:
25+ just calling the ``get() `` (or even ``has() ``) method of the ``flashbag `` will
26+ start a session. This may hurt your application performance because all users will
27+ receive a session cookie. To avoid this behavior, add a check before trying to
28+ access the flash messages:
2829
2930..code-block ::html+jinja
3031
31- {% if app.session.started %}
32+ {% if app.request.hasPreviousSession %}
3233 {% for flashMessage in app.session.flashbag.get('notice') %}
3334 <div class="flash-notice">
3435 {{ flashMessage }}
3536 </div>
3637 {% endfor %}
3738 {% endif %}
38-
39- Another scenario where session cookies will be automatically sent is when the
40- requested URL is covered by a firewall, even when anonymous users can access
41- to that URL:
42-
43- ..code-block ::yaml
44-
45- # app/config/security.yml
46- security :
47- firewalls :
48- main :
49- pattern :^/
50- form_login :~
51- anonymous :~
52-
53- This behavior is caused because in Symfony applications, anonymous users are
54- technically authenticated.