Jonah Katz
Jonah Katz

Reputation: 5298

Symfony 2 Session headers already sent?

Im trying to start (or access) a session like so :

    $session = new Session();
    echo $session->getId();

Which according to the doc should be all i need because the session gets auto started (http://symfony.com/doc/master/components/http_foundation/sessions.html) :

While it is recommended to explicitly start a session, a sessions will actually start 
on demand, that is, if any session request is made to read/write session data.

Nevertheless, im getting the error

Failed to start the session because headers have already been sent.

Heres the original controller thats calling the service:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Response;

        $auth = $this->get('authentication');
        $user_id = $auth->getUserId();

And then the getUserId function:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;

public function getUserId() {
    $session = new Session();
    echo $session->getId();

And if i change the getUserId to look like this:

public function getUserId() {
    $session = $this->getRequest()->getSession();
    echo $session->getId();

I get the error:

Call to a member function get() on a non-object

Upvotes: 0

Views: 4660

Answers (1)

Sgoettschkes
Sgoettschkes

Reputation: 13214

You are looking at the documentation of the stand-alone component "HTTP Foundation". This means that you have to very careful about what applies when you use the full-stack framework symfony2.

Symfony2 already takes care of the Request/Response and the session, so you don't need to create any Session object. You can read about how to use the session in the normal documentation, Chapter Controller.

To access a session in your controller, all you need is

$session = $this->getRequest()->getSession();

If you want to access the session inside a service, you need to pass the service "Request" as a dependency in your service.yml and than access the session through

$session = $request->getSession();

If you are not used to it, the Service Container Chapter has some descriptions.

Upvotes: 2

Related Questions