Sessions

Symfony provides a session object and several utilities that you can use tostore information about the user between requests.

Configuration

Sessions are provided by the HttpFoundation component, which is included inall Symfony applications, no matter how you installed it. Before using thesessions, check their default configuration:

  • YAML
  1. # config/packages/framework.yaml
  2. framework:
  3. session:
  4. # enables the support of sessions in the app
  5. enabled: true
  6. # ID of the service used for session storage.
  7. # NULL = means that PHP's default session mechanism is used
  8. handler_id: null
  9. # improves the security of the cookies used for sessions
  10. cookie_secure: 'auto'
  11. cookie_samesite: 'lax'
  • XML
  1. <!-- config/packages/framework.xml -->
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <container xmlns="http://symfony.com/schema/dic/services"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:framework="http://symfony.com/schema/dic/symfony"
  6. xsi:schemaLocation="http://symfony.com/schema/dic/services
  7. https://symfony.com/schema/dic/services/services-1.0.xsd
  8. http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
  9.  
  10. <framework:config>
  11. <!--
  12. enabled: enables the support of sessions in the app
  13. handler-id: ID of the service used for session storage
  14. NULL means that PHP's default session mechanism is used
  15. cookie-secure and cookie-samesite: improves the security of the cookies used for sessions
  16. -->
  17. <framework:session enabled="true"
  18. handler-id="null"
  19. cookie-secure="auto"
  20. cookie-samesite="lax"/>
  21. </framework:config>
  22. </container>
  • PHP
  1. // config/packages/framework.php
  2. $container->loadFromExtension('framework', [
  3. 'session' => [
  4. // enables the support of sessions in the app
  5. 'enabled' => true,
  6. // ID of the service used for session storage
  7. // NULL means that PHP's default session mechanism is used
  8. 'handler_id' => null,
  9. // improves the security of the cookies used for sessions
  10. 'cookie_secure' => 'auto',
  11. 'cookie_samesite' => 'lax',
  12. ],
  13. ]);

Setting the handler_id config option to null means that Symfony willuse the native PHP session mechanism. The session metadata files will be storedoutside of the Symfony application, in a directory controlled by PHP. Althoughthis usually simplify things, some session expiration related options may notwork as expected if other applications that write to the same directory haveshort max lifetime settings.

If you prefer, you can use the session.handler.native_file service ashandler_id to let Symfony manage the sessions itself. Another useful optionis save_path, which defines the directory where Symfony will store thesession metadata files:

  • YAML
  1. # config/packages/framework.yaml
  2. framework:
  3. session:
  4. # ...
  5. handler_id: 'session.handler.native_file'
  6. save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
  • XML
  1. <!-- config/packages/framework.xml -->
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <container xmlns="http://symfony.com/schema/dic/services"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:framework="http://symfony.com/schema/dic/symfony"
  6. xsi:schemaLocation="http://symfony.com/schema/dic/services
  7. https://symfony.com/schema/dic/services/services-1.0.xsd
  8. http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
  9.  
  10. <framework:config>
  11. <framework:session enabled="true"
  12. handler-id="session.handler.native_file"
  13. save-path="%kernel.project_dir%/var/sessions/%kernel.environment%"/>
  14. </framework:config>
  15. </container>
  • PHP
  1. // config/packages/framework.php
  2. $container->loadFromExtension('framework', [
  3. 'session' => [
  4. // ...
  5. 'handler_id' => 'session.handler.native_file',
  6. 'save_path' => '%kernel.project_dir%/var/sessions/%kernel.environment%',
  7. ],
  8. ]);

Check out the Symfony config reference to learn more about the other availableSession configuration options. Also, if youprefer to store session metadata in a database instead of the filesystem,check out this article: How to Use PdoSessionHandler to Store Sessions in the Database.

Basic Usage

Symfony provides a session service that is injected in your services andcontrollers if you type-hint an argument withSessionInterface:

  1. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  2.  
  3. class SomeService
  4. {
  5. private $session;
  6.  
  7. public function __construct(SessionInterface $session)
  8. {
  9. $this->session = $session;
  10. }
  11.  
  12. public function someMethod()
  13. {
  14. // stores an attribute in the session for later reuse
  15. $this->session->set('attribute-name', 'attribute-value');
  16.  
  17. // gets an attribute by name
  18. $foo = $this->session->get('foo');
  19.  
  20. // the second argument is the value returned when the attribute doesn't exist
  21. $filters = $this->session->get('filters', []);
  22.  
  23. // ...
  24. }
  25. }

Tip

Every SessionInterface implementation is supported. If you have yourown implementation, type-hint this in the argument instead.

Stored attributes remain in the session for the remainder of that user's session.By default, session attributes are key-value pairs managed with theAttributeBagclass.

If your application needs are complex, you may prefer to usenamespaced session attributes which are managed with theNamespacedAttributeBagclass. Before using them, override the session service definition to replacethe default AttributeBag by the NamespacedAttributeBag:

  • YAML
  1. # config/services.yaml
  2. session:
  3. public: true
  4. class: Symfony\Component\HttpFoundation\Session\Session
  5. arguments: ['@session.storage', '@session.namespacedattributebag', '@session.flash_bag']
  6.  
  7. session.namespacedattributebag:
  8. class: Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag

Avoid Starting Sessions for Anonymous Users

Sessions are automatically started whenever you read, write or even check forthe existence of data in the session. This may hurt your application performancebecause all users will receive a session cookie. In order to prevent that, youmust completely avoid accessing the session.

For example, if your templates include some code to display theflash messages, sessions will start even if the useris not logged in and even if you haven't created any flash messages. To avoidthis behavior, add a check before trying to access the flash messages:

  1. {# this check prevents starting a session when there are no flash messages #}
  2. {% if app.request.hasPreviousSession %}
  3. {% for message in app.flashes('notice') %}
  4. <div class="flash-notice">
  5. {{ message }}
  6. </div>
  7. {% endfor %}
  8. {% endif %}

More about Sessions