Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Doctrine
  4. How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia
  • Setting Up the MongoDB Collection

How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database

Edit this page

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

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

How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database

The default Symfony session storage writes the session information to files. Some medium to large websites use a NoSQL database called MongoDB to store the session values instead of files, because databases are easier to use and scale in a multi-webserver environment.

Symfony has a built-in solution for NoSQL database session storage called MongoDbSessionHandler. MongoDB is an open-source document database that provides high performance, high availability and automatic scaling. This article assumes that you have already installed and configured a MongoDB server. To use it, you just need to change/add some parameters in the main configuration file:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# app/config/config.yml
framework:
    session:
        # ...
        handler_id:  session.handler.mongo
        cookie_lifetime: 2592000 # optional, it is set to 30 days here
        gc_maxlifetime: 2592000 # optional, it is set to 30 days here

services:
    # ...
    mongo_client:
        class: MongoClient
        # if using a username and password
        arguments: ['mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017']
        # if not using a username and password
        arguments: ['mongodb://%mongodb_host%:27017']
    session.handler.mongo:
        class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler
        arguments: ['@mongo_client', '%mongo.session.options%']
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
26
27
28
29
30
31
32
33
34
<?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
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config>
        <!-- ... -->

        <!-- cookie-lifetime and gc-maxlifetime are optional and set to
             30 days in this example -->
        <framework:session handler-id="session.handler.mongo"
            cookie-lifetime="2592000"
            gc-maxlifetime="2592000"
        />
    </framework:config>

    <services>
        <service id="mongo_client" class="MongoClient">
            <!-- if using a username and password -->
            <argument>mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017</argument>

            <!-- if not using a username and password -->
            <argument>mongodb://%mongodb_host%:27017</argument>
        </service>

        <service id="session.handler.mongo" class="Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler">
            <argument type="service">mongo_client</argument>
            <argument>%mongo.session.options%</argument>
        </service>
</container>
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\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;

$container->loadFromExtension('framework', array(
    'session' => array(
        // ...
        'handler_id'      => 'session.handler.mongo',
        'cookie_lifetime' => 2592000, // optional, it is set to 30 days here
        'gc_maxlifetime'  => 2592000, // optional, it is set to 30 days here
    ),
));

$container->register('mongo_client', \MongoClient::class)
    ->setArguments(array(
        // if using a username and password
        array('mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017'),
        // if not using a username and password
        array('mongodb://%mongodb_host%:27017'),
    ));

$container->register('session.handler.mongo', MongoDbSessionHandler::class)
    ->setArguments(array(
        new Reference('mongo_client'),
        '%mongo.session.options%',
    ));

The parameters used above should be defined somewhere in your application, often in your main parameters configuration:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
# app/config/parameters.yml
parameters:
    # ...
    mongo.session.options:
        database: session_db # your MongoDB database name
        collection: session  # your MongoDB collection name
    mongodb_host: 1.2.3.4 # your MongoDB server's IP
    mongodb_username: my_username
    mongodb_password: my_password
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <parameters>
        <parameter key="mongo.session.options" type="collection">
            <!-- your MongoDB database name -->
            <parameter key="database">session_db</parameter>
            <!-- your MongoDB collection name -->
            <parameter key="collection">session</parameter>
        </parameter>
        <!-- your MongoDB server's IP -->
        <parameter key="mongodb_host">1.2.3.4</parameter>
        <parameter key="mongodb_username">my_username</parameter>
        <parameter key="mongodb_password">my_password</parameter>
    </parameters>
</container>
1
2
3
4
5
6
7
8
9
use Symfony\Component\DependencyInjection\Reference;

$container->setParameter('mongo.session.options', array(
    'database'   => 'session_db', // your MongoDB database name
    'collection' => 'session',  // your MongoDB collection name
));
$container->setParameter('mongodb_host', '1.2.3.4'); // your MongoDB server's IP
$container->setParameter('mongodb_username', 'my_username');
$container->setParameter('mongodb_password', 'my_password');

Setting Up the MongoDB Collection

Because MongoDB uses dynamic collection schemas, you do not need to do anything to initialize your session collection. However, you may want to add an index to improve garbage collection performance. From the MongoDB shell:

1
2
use session_db
db.session.ensureIndex( { "expires_at": 1 }, { expireAfterSeconds: 0 } )
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Save your teams and projects before they sink

Save your teams and projects before they sink

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

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

Avatar of Alessio Pierobon, a Symfony contributor

Thanks Alessio Pierobon (@alepsys) for being a Symfony contributor

2 commits • 6 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