4
4
Avoid Starting Sessions for Anonymous Users
5
5
===========================================
6
6
7
- Sessions in Symfony applications are automatically started whenever they are necessary.
8
- This includes writing in the user'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 whenever you 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 .
11
11
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 :
15
15
16
16
.. code-block :: html+jinja
17
17
@@ -22,33 +22,17 @@ template code commonly used to display flash messages:
22
22
{% endfor %}
23
23
24
24
Even 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:
28
29
29
30
.. code-block :: html+jinja
30
31
31
- {% if app.session.started %}
32
+ {% if app.request.hasPreviousSession %}
32
33
{% for flashMessage in app.session.flashbag.get('notice') %}
33
34
<div class="flash-notice">
34
35
{{ flashMessage }}
35
36
</div>
36
37
{% endfor %}
37
38
{% 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.
0 commit comments