Symfony2 empty session id in service

I am using symfony 2.5 and I have the following monologue service.

<?php

namespace Megogo\CoreBundle;

use Symfony\Component\HttpFoundation\Session\Session;

class SessionRequestProcessor
{
    /**
     * @var \Symfony\Component\HttpFoundation\Session\Session
     */
    protected $session;

    /**
     * @var
     */
    private $token;

    public function __construct( Session $session)
    {
        $this->session = $session;
    }

    public function processRecord(array $record)
    {

        if (null === $this->token) {
            try {
                $this->token = $this->session->getId();
            } catch (\RuntimeException $e) {
                $this->token = '????????';
            }

        }
        $record['extra']['token'] = $this->token;

        return $record;
    }
} 

      

service.yml

services:
    monolog.formatter.session_request:
        class: Monolog\Formatter\LineFormatter
        arguments:
            - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%%\n"

    monolog.processor.session_request:
        class: Megogo\CoreBundle\SessionRequestProcessor
        arguments:  ["@session"]
        tags:
            - { name: monolog.processor, method: processRecord }

      

I am getting an example from the official documentation. Adding a session / request token

I have a problem that $this->session->getId()

returns an empty string. If I add $session->start();

everything works. I can get the session id. But this is weird because in my other services everything works without this workaround. And when I do app/console cache:clear

I have a mistakeFailed to start the session: already started by PHP.

+3


source to share


2 answers


I had a similar problem.

I solved it by adding to the controller

$this->get('session')->start();

      

In your case, you can just add the following line before trying to get the session id



$this->session->start();

      

Don't worry about calling "start ()" when the session is already started - it will check and just skip (re) start it.

The current version (2.6) of Symfony does not have a config property that will force the session to auto_start

+2


source


The official docs read:

Symfony sessions are incompatible with php.ini directive session.auto_start = 1 . This directive must be disabled in php.ini, web server directives or .htaccess.



Maybe try this?

0


source







All Articles