diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 99498b50a7a..49a65cf8462 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -166,6 +166,7 @@ * :doc:`/cookbook/session/sessions_directory` * :doc:`/cookbook/session/php_bridge` * (configuration) :doc:`/cookbook/configuration/pdo_session_storage` + * :doc:`/cookbook/session/avoid_session_start` * **symfony1** diff --git a/cookbook/session/avoid_session_start.rst b/cookbook/session/avoid_session_start.rst new file mode 100644 index 00000000000..8736f484ad6 --- /dev/null +++ b/cookbook/session/avoid_session_start.rst @@ -0,0 +1,38 @@ +.. index:: + single: Sessions, cookies + +Avoid Starting Sessions for Anonymous Users +=========================================== + +Sessions are automatically started whenever you read, write or even check for the +existence of data in the session. This means that if you need to avoid creating +a session cookie for some users, it can be difficult: you must *completely* avoid +accessing the session. + +For example, one common problem in this situation involves checking for flash +messages, which are stored in the session. The following code would guarantee +that a session is *always* started: + +.. code-block:: html+jinja + + {% for flashMessage in app.session.flashbag.get('notice') %} +
+ {{ flashMessage }} +
+ {% endfor %} + +Even if the user is not logged in and even if you haven't created any flash message, +just calling the ``get()`` (or even ``has()``) method of the ``flashbag`` will +start a session. This may hurt your application performance because all users will +receive a session cookie. To avoid this behavior, add a check before trying to +access the flash messages: + +.. code-block:: html+jinja + + {% if app.request.hasPreviousSession %} + {% for flashMessage in app.session.flashbag.get('notice') %} +
+ {{ flashMessage }} +
+ {% endfor %} + {% endif %} diff --git a/cookbook/session/index.rst b/cookbook/session/index.rst index 536ad02c3d8..0420126b48e 100644 --- a/cookbook/session/index.rst +++ b/cookbook/session/index.rst @@ -7,4 +7,5 @@ Sessions proxy_examples locale_sticky_session sessions_directory - php_bridge \ No newline at end of file + php_bridge + avoid_session_start \ No newline at end of file