Sessions

Sessions

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

Configuration

Sessions are provided by the HttpFoundation component, which is included in all Symfony applications, no matter how you installed it. Before using the sessions, 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 Symfony uses PHP default session mechanism
    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. <framework:config>
    10. <!--
    11. enabled: enables the support of sessions in the app
    12. handler-id: ID of the service used for session storage
    13. NULL means that Symfony uses PHP default session mechanism
    14. cookie-secure and cookie-samesite: improves the security of the cookies used for sessions
    15. -->
    16. <framework:session enabled="true"
    17. handler-id="null"
    18. cookie-secure="auto"
    19. cookie-samesite="lax"/>
    20. </framework:config>
    21. </container>
  • PHP

    1. // config/packages/framework.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->session()
    5. // enables the support of sessions in the app
    6. ->enabled(true)
    7. // ID of the service used for session storage
    8. // NULL means that Symfony uses PHP default session mechanism
    9. ->handlerId(null)
    10. // improves the security of the cookies used for sessions
    11. ->cookieSecure('auto')
    12. ->cookieSamesite('lax')
    13. ;
    14. };

Setting the handler_id config option to null means that Symfony will use the native PHP session mechanism. The session metadata files will be stored outside of the Symfony application, in a directory controlled by PHP. Although this usually simplify things, some session expiration related options may not work as expected if other applications that write to the same directory have short max lifetime settings.

If you prefer, you can use the session.handler.native_file service as handler_id to let Symfony manage the sessions itself. Another useful option is save_path, which defines the directory where Symfony will store the session 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. <framework:config>
    10. <framework:session enabled="true"
    11. handler-id="session.handler.native_file"
    12. save-path="%kernel.project_dir%/var/sessions/%kernel.environment%"/>
    13. </framework:config>
    14. </container>
  • PHP

    1. // config/packages/framework.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->session()
    5. // ...
    6. ->handlerId('session.handler.native_file')
    7. ->savePath('%kernel.project_dir%/var/sessions/%kernel.environment%')
    8. ;
    9. };

Check out the Symfony config reference to learn more about the other available Session configuration options. You can also store sessions in a database.

Basic Usage

The sessions is available througth the Request and the RequestStack. Symfony provides a request_stack service that is injected in your services and controllers if you type-hint an argument with Symfony\Component\HttpFoundation\RequestStack:

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

Deprecated since version 5.3: The SessionInterface and session service were deprecated in Symfony 5.3. Instead, inject the RequestStack service to get the session object of the current request.

Stored attributes remain in the session for the remainder of that user’s session. By default, session attributes are key-value pairs managed with the Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag class.

Deprecated since version 5.3: The NamespacedAttributeBag class is deprecated since Symfony 5.3. If you need this feature, you will have to implement the class yourself.

If your application needs are complex, you may prefer to use namespaced session attributes which are managed with the Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag class. Before using them, override the session_listener service definition to build your Session object with the default AttributeBag by the NamespacedAttributeBag:

  • YAML

    1. # config/services.yaml
    2. session.factory:
    3. autoconfigure: true
    4. class: App\Session\SessionFactory
    5. arguments:
    6. - '@request_stack'
    7. - '@session.storage.factory'
    8. - ['@session_listener', 'onSessionUsage']
    9. - '@session.namespacedattributebag'
    10. session.namespacedattributebag:
    11. class: Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag
  • XML

    1. <!-- config/services.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. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <service id="session" class="Symfony\Component\HttpFoundation\Session\Session" public="true">
    8. <argument type="service" id="session.storage"/>
    9. <argument type="service" id="session.namespacedattributebag"/>
    10. <argument type="service" id="session.flash_bag"/>
    11. </service>
    12. <service id="session.namespacedattributebag"
    13. class="Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag"
    14. />
    15. </services>
    16. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
    4. use Symfony\Component\HttpFoundation\Session\Session;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. $services->set('session', Session::class)
    8. ->public()
    9. ->args([
    10. ref('session.storage'),
    11. ref('session.namespacedattributebag'),
    12. ref('session.flash_bag'),
    13. ])
    14. ;
    15. $services->set('session.namespacedattributebag', NamespacedAttributeBag::class);
    16. };

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 may hurt your application performance because all users will receive a session cookie. In order to prevent that, you must completely avoid accessing the session.

More about Sessions

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.