|
| 1 | +.. index:: |
| 2 | + single: Sessions, cookies |
| 3 | + |
| 4 | +Avoid Starting Sessions for Anonymous Users |
| 5 | +=========================================== |
| 6 | + |
| 7 | +Sessions in Symfony applications are automatically started when 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 | +sent for every request. |
| 11 | + |
| 12 | +However, there are other scenarios when a session is started and therefore, a |
| 13 | +cookie will be created even for anonymous users. First, consider the following |
| 14 | +code commonly used to display flash messages: |
| 15 | + |
| 16 | +.. code-block:: html+jinja |
| 17 | + |
| 18 | + {% for flashMessage in app.session.flashbag.get('notice') %} |
| 19 | + <div class="flash-notice"> |
| 20 | + {{ flashMessage }} |
| 21 | + </div> |
| 22 | + {% endfor %} |
| 23 | + |
| 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: |
| 28 | + |
| 29 | +.. code-block:: html+jinja |
| 30 | + |
| 31 | + {% if app.session.started %} |
| 32 | + {% for flashMessage in app.session.flashbag.get('notice') %} |
| 33 | + <div class="flash-notice"> |
| 34 | + {{ flashMessage }} |
| 35 | + </div> |
| 36 | + {% endfor %} |
| 37 | + {% endif %} |
| 38 | + |
| 39 | +Another scenario where session cookies will be automatically sent is when the |
| 40 | +requested URL is covered by a firewall, no matter if 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