Talk To Us For FREE

We are in the Business of Support and that starts before you even become a client.

Symfony2 Store Sessions in the Database

Categories : Article, Symfony

With Symfony 2 development you have a built in solution for storing sessions in the database. This is called PdoSessionHandler. In order to use this option in Symfony 2, you need to change a few parameters here and there. The config.yml file is a good start.

# app/config/config.yml
        # ...
        handler_id: session.handler.pdo

        db_table:    session
        db_id_col:   session_id
        db_data_col: session_value
        db_time_col: session_time

        class: PDO
            dsn:      "mysql:dbname=mydatabase"
            user:     myuser
            password: mypassword
            - [setAttribute, [3, 2]] # \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION

        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        arguments: ["@pdo", "%pdo.db_options%"]

Here are the details:
db_table is the name of the session table in the database
db_id_col is the name of the id column in your session table (VARCHAR(255) or larger)
db_data_col is the name of the value column in your session table (TEXT or CLOB)
db_time_col is the name of the time column in your session table (INTEGER)

Sharing Database Connection Information
The database connection settings in the given example are defines for session storage connections only. This works fine if you use separate database for session data. If you require to store the session data in the same database as your project data, the parameters.yml file needs to be tweaked. By referencing the database related parameters.

    class: PDO
        - "mysql:host=%database_host%;port=%database_port%;dbname=%database_name%"
        - "%database_user%"
        - "%database_password%"

Symfony 2 defaults to store the session information in files. But many medium or large websites prefer to store this information to databases. Databases can easily scale in a multi website environment. These were a few tips to configure the session information to be stored in the database instead of files.

[Total: 0    Average: 0/5]