Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Sessions
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Configuration
  • Basic Usage
  • Avoid Starting Sessions for Anonymous Users
  • More about Sessions

Sessions

Edit this page

Warning: You are browsing the documentation for Symfony 4.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
# config/packages/framework.yaml
framework:
    # Enables session support. Note that the session will ONLY be started if you read or write from it.
    # Remove or comment this section to explicitly disable session support.
    session:
        # ID of the service used for session storage
        # NULL means that Symfony uses PHP default session mechanism
        handler_id: null
        # improves the security of the cookies used for sessions
        cookie_secure: auto
        cookie_samesite: lax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config>
        <!--
            Enables session support. Note that the session will ONLY be started if you read or write from it.
            Remove or comment this section to explicitly disable session support.
            handler-id: ID of the service used for session storage
                        NULL means that Symfony uses PHP default session mechanism
            cookie-secure and cookie-samesite: improves the security of the cookies used for sessions
        -->
        <framework:session handler-id="null"
                           cookie-secure="auto"
                           cookie-samesite="lax"/>
    </framework:config>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
// config/packages/framework.php
$container->loadFromExtension('framework', [
    // Enables session support. Note that the session will ONLY be started if you read or write from it.
    // Remove or comment this section to explicitly disable session support.
    'session' => [
        // ID of the service used for session storage
        // NULL means that Symfony uses PHP default session mechanism
        'handler_id' => null,
        // improves the security of the cookies used for sessions
        'cookie_secure' => 'auto',
        'cookie_samesite' => 'lax',
    ],
]);

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
  • XML
  • PHP
1
2
3
4
5
6
# config/packages/framework.yaml
framework:
    session:
        # ...
        handler_id: 'session.handler.native_file'
        save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- config/packages/framework.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config>
        <framework:session enabled="true"
                           handler-id="session.handler.native_file"
                           save-path="%kernel.project_dir%/var/sessions/%kernel.environment%"/>
    </framework:config>
</container>
1
2
3
4
5
6
7
8
// config/packages/framework.php
$container->loadFromExtension('framework', [
    'session' => [
        // ...
        'handler_id' => 'session.handler.native_file',
        'save_path' => '%kernel.project_dir%/var/sessions/%kernel.environment%',
    ],
]);

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

Symfony provides a session service that is injected in your services and controllers if you type-hint an argument with SessionInterface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class SomeService
{
    private $session;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    public function someMethod()
    {
        // stores an attribute in the session for later reuse
        $this->session->set('attribute-name', 'attribute-value');

        // gets an attribute by name
        $foo = $this->session->get('foo');

        // the second argument is the value returned when the attribute doesn't exist
        $filters = $this->session->get('filters', []);

        // ...
    }
}

Tip

Every SessionInterface implementation is supported. If you have your own 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 the AttributeBag class.

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

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

session.namespacedattributebag:
    class: Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="session" class="Symfony\Component\HttpFoundation\Session\Session" public="true">
            <argument type="service" id="session.storage"/>
            <argument type="service" id="session.namespacedattributebag"/>
            <argument type="service" id="session.flash_bag"/>
        </service>

        <service id="session.namespacedattributebag"
            class="Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag"
        />
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
use Symfony\Component\HttpFoundation\Session\Session;

return function(ContainerConfigurator $configurator) {
    $services = $configurator->services();

    $services->set('session', Session::class)
        ->public()
        ->args([
            ref('session.storage'),
            ref('session.namespacedattributebag'),
            ref('session.flash_bag'),
        ])
    ;

    $services->set('session.namespacedattributebag', NamespacedAttributeBag::class);
};

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

  • Store Sessions in a Database
  • Making the Locale "Sticky" during a User's Session
  • Bridge a legacy Application with Symfony Sessions
  • Session Proxy Examples
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    The life jacket for your team and your project

    The life jacket for your team and your project

    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Jérémy Halin, a Symfony contributor

    Thanks Jérémy Halin for being a Symfony contributor

    1 commit • 9 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia