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. Cookbook
  4. Configuration
  5. How to use PdoSessionHandler to store Sessions in the Database
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Sharing your Database Connection Information
  • Example SQL Statements
    • 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 2.2, which is no longer maintained.

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

How to use PdoSessionHandler to store Sessions in the Database

The default session storage of Symfony2 writes the session information to file(s). 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 multi-webserver environment.

Symfony2 has a built-in solution for database session storage called PdoSessionHandler. To use it, you just need to change some parameters in config.yml (or the configuration format of your choice):

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
  • XML
  • 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
# 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%"]
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>
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);
  • 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
  • XML
  • PHP
1
2
3
4
5
6
pdo:
    class: PDO
    arguments:
        - "mysql:host=%database_host%;port=%database_port%;dbname=%database_name%"
        - "%database_user%"
        - "%database_password%"
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>
1
2
3
4
5
$pdoDefinition = new Definition('PDO', array(
    'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%',
    '%database_user%',
    '%database_password%',
));

Example SQL Statements

MySQL

The SQL statement for creating the needed database table might look like the following (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

For PostgreSQL, the statement should look like this:

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

For MSSQL, the statement might look like the following:

1
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]

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    No stress: we've got you covered with our 116 automated quality checks of your code

    No stress: we've got you covered with our 116 automated quality checks of your code

    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Symfony footer

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

    Avatar of Alexis Lefebvre, a Symfony contributor

    Thanks Alexis Lefebvre for being a Symfony contributor

    14 commits • 1.09K 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