Using Redis for session handling in Symfony 4.1+

How to use Redis in Symfony project to manage user sessions.

Handling sessions outside of the local filesystem is getting even more usual in a cloud-based environment. Using Redis is one of the popular solutions for this purpose.

Symfony 4.1 introduced the RedisSessionHandler (see PR #24781) but its usage is not very much documented. The good news is that you don't need any third-party library to make it work, apart from the PHP Redis extension.

Install the Redis extension for PHP

The easiest way to get the redis extension enabled is to use your own PHP Docker container based on the official PHP image, by creating a Dockerfile file (stored at the root of the project in this article):

FROM php:7.2-fpm

# ...

# Install PHP Redis extension
RUN pecl install -o -f redis \
  &&  rm -rf /tmp/pear \
  &&  docker-php-ext-enable redis

Create Docker containers for PHP and Redis

Create a docker-compose.yml file to define the Redis and PHP containers:

version: '3'
    build: .
      - redis
      # The "redis" matches the name of the container defined below
      REDIS_HOST: redis
      REDIS_PORT: 6379

    image: redis:4-alpine

Start containers:

docker-compose up -d

Note that you can now access the Redis CLI running:

docker-compose exec redis redis-cli

Symfony configuration

Define a Symfony service for the Redis connection and set it as a constructor argument to the RedisSessionHandler service:

# config/services.yaml
        class: Redis
            - method: connect
                  - '%env(REDIS_HOST)%'
                  - '%env(int:REDIS_PORT)%'
            # If you need key prefix, uncomment line belows
            # - method: setOption
            #   arguments:
            #       - !php/const Redis::OPT_PREFIX
            #       - 'my_prefix'

            - '@Redis'

To learn more about the advanced usage of %env(…)% introduced in Symfony 3.4 (like the int processor that I have used here), have a look to the Symfony documentation.

You can now make use of the service as your session handler:

# config/packages/framework.yaml
        handler_id: Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler

You're done!