Session sometimes works, sometimes doesn't?

Silverstripe Version:
4.4.5
Question:
OK, this is just straight out of the official doc:

Here I see the value saved into session

    $session = $request->getSession();
    $session->set('MyVal', '1');
    Debug::show($session);

image

Now I take out $session->set('MyVal', '1');

$session = $request->getSession();
Debug::show($session);

and — ???
image

I had this issue before - but it resolved itself before I could figure out what was going no - now tonight it came up again :confused:

However, if I save data via $_SESSION, it works (save and read, no problem) - and it will work if I call “save” function and pass in $request

$session->save($request);

So, how does it really work? The documentation seems clear, but the same issue comes and goes and I’m already confused like

It looks like you’ve already found the answer.
Session component does not persist its state on every “Session::set”, but does it only once per request on Session::save invocation. That happens in SessionMiddleware. Note that the middleware does not ::start the session, it merely performs ::init. The ::start is done lazily within the ::save method.
When you do Debug::show($session), it flushes HTTP headers before the middleware can persist the session, so the cookie with the session id cannot be set.

1 Like

Thanks @dnsl48 ! In the next morning when I had a closer look on Session::class, I found SilverStripe has its own session data built on top of $_SESSION, and yes, like you said, it won’t get properly called until later stage.

Actually, I also figured out where my problem is:

When I did Session::set, I did it in handleAction function, and then die;- this is why it couldn’t get saved!

Cheers
Leo