WARNING: You are browsing the documentation for Symfony 2.3 which is not maintained anymore. Consider upgrading your projects to Symfony 4.3.

How to Use PdoSessionHandler to Store Sessions in the Database

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:

New in version 2.1: In Symfony 2.1 the class and namespace are slightly modified. You can now find the session storage classes in the Session\Storage namespace: Symfony\Component\HttpFoundation\Session\Storage. Also, note that in Symfony 2.1 you should configure handler_id not storage_id like in Symfony 2.0. Below, you'll notice that %session.storage.options% is not used anymore.

  • YAML
     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
    # app/config/config.yml
    framework:
        session:
            # ...
            handler_id: session.handler.pdo
    
    parameters:
        pdo.db_options:
            db_table:    session
            db_id_col:   session_id
            db_data_col: session_value
            db_time_col: session_time
    
    services:
        pdo:
            class: PDO
            arguments:
                dsn:      "mysql:dbname=mydatabase"
                user:     myuser
                password: mypassword
            calls:
                - [setAttribute, [3, 2]] # \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION
    
        session.handler.pdo:
            class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
            arguments: ['@pdo', '%pdo.db_options%']
    
  • XML
     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
    <!-- app/config/config.xml -->
    <framework:config>
        <framework:session handler-id="session.handler.pdo" cookie-lifetime="3600" auto-start="true"/>
    </framework:config>
    
    <parameters>
        <parameter key="pdo.db_options" type="collection">
            <parameter key="db_table">session</parameter>
            <parameter key="db_id_col">session_id</parameter>
            <parameter key="db_data_col">session_value</parameter>
            <parameter key="db_time_col">session_time</parameter>
        </parameter>
    </parameters>
    
    <services>
        <service id="pdo" class="PDO">
            <argument>mysql:dbname=mydatabase</argument>
            <argument>myuser</argument>
            <argument>mypassword</argument>
            <call method="setAttribute">
                <argument type="constant">PDO::ATTR_ERRMODE</argument>
                <argument type="constant">PDO::ERRMODE_EXCEPTION</argument>
            </call>
        </service>
    
        <service id="session.handler.pdo" class="Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler">
            <argument type="service" id="pdo" />
            <argument>%pdo.db_options%</argument>
        </service>
    </services>
    
  • PHP
     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
    // app/config/config.php
    use Symfony\Component\DependencyInjection\Definition;
    use Symfony\Component\DependencyInjection\Reference;
    
    $container->loadFromExtension('framework', array(
        ...,
        'session' => array(
            // ...,
            'handler_id' => 'session.handler.pdo',
        ),
    ));
    
    $container->setParameter('pdo.db_options', array(
        'db_table'      => 'session',
        'db_id_col'     => 'session_id',
        'db_data_col'   => 'session_value',
        'db_time_col'   => 'session_time',
    ));
    
    $pdoDefinition = new Definition('PDO', array(
        'mysql:dbname=mydatabase',
        'myuser',
        'mypassword',
    ));
    $pdoDefinition->addMethodCall('setAttribute', array(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION));
    $container->setDefinition('pdo', $pdoDefinition);
    
    $storageDefinition = new Definition('Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler', array(
        new Reference('pdo'),
        '%pdo.db_options%',
    ));
    $container->setDefinition('session.handler.pdo', $storageDefinition);
    

These are parameters that you must configure:

db_table
The name of the session table in your database.
db_id_col
The name of the id column in your session table (VARCHAR(255) or larger).
db_data_col
The name of the value column in your session table (TEXT or CLOB).
db_time_col:
The name of the time 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:

  • YAML
    1
    2
    3
    4
    5
    6
    7
    services:
        pdo:
            class: PDO
            arguments:
                - 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%'
                - '%database_user%'
                - '%database_password%'
    
  • XML
    1
    2
    3
    4
    5
    <service id="pdo" class="PDO">
        <argument>mysql:host=%database_host%;port=%database_port%;dbname=%database_name%</argument>
        <argument>%database_user%</argument>
        <argument>%database_password%</argument>
    </service>
    
  • PHP
    1
    2
    3
    4
    5
    $pdoDefinition = new Definition('PDO', array(
        'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%',
        '%database_user%',
        '%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 `session` (
    `session_id` varchar(255) NOT NULL,
    `session_value` text NOT NULL,
    `session_time` int(11) NOT NULL,
    PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PostgreSQL

1
2
3
4
5
6
CREATE TABLE session (
    session_id character varying(255) NOT NULL,
    session_value text NOT NULL,
    session_time integer NOT NULL,
    CONSTRAINT session_pkey PRIMARY KEY (session_id)
);

Microsoft SQL Server

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
CREATE TABLE [dbo].[session](
    [session_id] [nvarchar](255) NOT NULL,
    [session_value] [ntext] NOT NULL,
    [session_time] [int] NOT NULL,
    PRIMARY KEY CLUSTERED(
        [session_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 get noticed when such an error happens.

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