Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • 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
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Doctrine
  4. How to Use PdoSessionHandler to Store Sessions in the Database
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Configuring the Table and Column Names
  • Sharing your Database Connection Information
  • Preparing the Database to Store Sessions
    • MySQL
    • PostgreSQL
    • Microsoft SQL Server

How to Use PdoSessionHandler to Store Sessions in the Database

Edit this page

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

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

How to Use PdoSessionHandler to Store Sessions in the Database

The default Symfony session storage writes the session information to files. Most medium to large websites use a database to store the session values instead of files, because databases are easier to use and scale in a multiple web server environment.

Symfony has a built-in solution for database session storage called PdoSessionHandler. To use it, you just need to change some parameters in the main configuration file:

1
2
3
4
5
6
7
8
9
10
11
12
13
# app/config/config.yml
framework:
    session:
        # ...
        handler_id: session.handler.pdo

services:
    session.handler.pdo:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        public:    false
        arguments:
            - 'mysql:dbname=mydatabase'
            - { db_username: myuser, db_password: mypassword }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- app/config/config.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
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config>
        <framework:session handler-id="session.handler.pdo" cookie-lifetime="3600" auto-start="true"/>
    </framework:config>

    <services>
        <service id="session.handler.pdo" class="Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler" public="false">
            <argument>mysql:dbname=mydatabase</argument>
            <argument type="collection">
                <argument key="db_username">myuser</argument>
                <argument key="db_password">mypassword</argument>
            </argument>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// app/config/config.php

use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;

// ...
$container->loadFromExtension('framework', array(
    // ...
    'session' => array(
        // ...
        'handler_id' => 'session.handler.pdo',
    ),
));

$container->register('session.handler.pdo', PdoSessionHandler::class)
    ->setArguments(array(
        'mysql:dbname=mydatabase',
        array('db_username' => 'myuser', 'db_password' => 'mypassword'),
    ));

Configuring the Table and Column Names

This will expect a sessions table with a number of different columns. The table name, and all of the column names, can be configured by passing a second array argument to PdoSessionHandler:

1
2
3
4
5
6
7
8
9
# app/config/config.yml
services:
    # ...
    session.handler.pdo:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        public:    false
        arguments:
            - 'mysql:dbname=mydatabase'
            - { db_table: sessions, db_username: myuser, db_password: mypassword }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- app/config/config.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
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="session.handler.pdo" class="Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler" public="false">
            <argument>mysql:dbname=mydatabase</argument>
            <argument type="collection">
                <argument key="db_table">sessions</argument>
                <argument key="db_username">myuser</argument>
                <argument key="db_password">mypassword</argument>
            </argument>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
// app/config/config.php

use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
// ...

$container->register('session.handler.pdo', PdoSessionHandler::class)
    ->setArguments(array(
        'mysql:dbname=mydatabase',
        array('db_table' => 'sessions', 'db_username' => 'myuser', 'db_password' => 'mypassword'),
    ));

These are parameters that you must configure:

db_table (default sessions):
The name of the session table in your database;
db_id_col (default sess_id):
The name of the id column in your session table (VARCHAR(128));
db_data_col (default sess_data):
The name of the value column in your session table (BLOB);
db_time_col (default sess_time):
The name of the time column in your session table (INTEGER);
db_lifetime_col (default sess_lifetime):
The name of the lifetime column in your session table (INTEGER).

Sharing your Database Connection Information

With the given configuration, the database connection settings are defined for the session storage connection only. This is OK when you use a separate database for the session data.

But if you'd like to store the session data in the same database as the rest of your project's data, you can use the connection settings from the parameters.yml file by referencing the database-related parameters defined there:

1
2
3
4
5
6
7
services:
    session.handler.pdo:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        public:    false
        arguments:
            - 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%'
            - { db_username: '%database_user%', db_password: '%database_password%' }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="session.handler.pdo" class="Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler" public="false">
            <argument>mysql:host=%database_host%;port=%database_port%;dbname=%database_name%</argument>
            <argument type="collection">
                <argument key="db_username">%database_user%</argument>
                <argument key="db_password">%database_password%</argument>
            </argument>
        </service>
    </services>
</container>
1
2
3
4
5
// ...
$storageDefinition = new Definition(PdoSessionHandler::class, array(
    'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%',
    array('db_username' => '%database_user%', 'db_password' => '%database_password%')
));

Preparing the Database to Store Sessions

Before storing sessions in the database, you must create the table that stores the information. The following sections contain some examples of the SQL statements you may use for your specific database engine.

MySQL

1
2
3
4
5
6
CREATE TABLE `sessions` (
    `sess_id` VARCHAR(128) NOT NULL PRIMARY KEY,
    `sess_data` BLOB NOT NULL,
    `sess_time` INTEGER UNSIGNED NOT NULL,
    `sess_lifetime` MEDIUMINT NOT NULL
) COLLATE utf8_bin, ENGINE = InnoDB;

Note

A BLOB column type can only store up to 64 kb. If the data stored in a user's session exceeds this, an exception may be thrown or their session will be silently reset. Consider using a MEDIUMBLOB if you need more space.

PostgreSQL

1
2
3
4
5
6
CREATE TABLE sessions (
    sess_id VARCHAR(128) NOT NULL PRIMARY KEY,
    sess_data BYTEA NOT NULL,
    sess_time INTEGER NOT NULL,
    sess_lifetime INTEGER NOT NULL
);

Microsoft SQL Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CREATE TABLE [dbo].[sessions](
    [sess_id] [nvarchar](255) NOT NULL,
    [sess_data] [ntext] NOT NULL,
    [sess_time] [int] NOT NULL,
    [sess_lifetime] [int] NOT NULL,
    PRIMARY KEY CLUSTERED(
        [sess_id] ASC
    ) WITH (
        PAD_INDEX  = OFF,
        STATISTICS_NORECOMPUTE  = OFF,
        IGNORE_DUP_KEY = OFF,
        ALLOW_ROW_LOCKS  = ON,
        ALLOW_PAGE_LOCKS  = ON
    ) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Caution

If the session data doesn't fit in the data column, it might get truncated by the database engine. To make matters worse, when the session data gets corrupted, PHP ignores the data without giving a warning.

If the application stores large amounts of session data, this problem can be solved by increasing the column size (use BLOB or even MEDIUMBLOB). When using MySQL as the database engine, you can also enable the strict SQL mode to be notified when such an error happens.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

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

    Avatar of Chris Taylor, a Symfony contributor

    Thanks Chris Taylor for being a Symfony contributor

    1 commit • 4 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 Meilisearch