October 21, 2024
Chicago 12, Melborne City, USA
PHP

How should one get Session object in a controller on Symfony 5.3?


I’m working on a cart system for users who are not logged in in Symfony. I use the session ID to identify the user’s cart, and here is the code I use to get the session ID:

use Symfony\Component\HttpFoundation\Request;

public function index(Request $request): Response
{
    $session = $request->getSession();
    if (!$session->isStarted()) {
        $session->start();
    }
    $sessionId = $session->getId();
    return new Response('Session ID: ' . $sessionId);
}

It was working perfectly until I logged into an account to test the cart for a logged-in user.

After logging out, the session ID always returns an empty string ("").

I tried setting invalidate_session to false in security.yaml, but it didn’t solve the problem.

Here is my security.yaml configuration:

firewalls:
    my_firewall:
        logout:
            invalidate_session: false
        anonymous: true

And my session configuration in framework.yaml:

framework:
    session:
        handler_id: ~
        cookie_secure: auto
        cookie_samesite: lax

Even when I try to start the session manually with $session->start(), the session ID changes with each request, and I can’t keep a consistent session ID.

Symfony version: 7.1
Environment: Development

I’ve tried several things, but I still can’t figure out why the session ID keeps returning an empty string or changes on each request. Any ideas on what might be causing this issue and how to resolve it?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video