I'm experiencing an issue in Grav where I'm trying to set a custom session variable and then retrieve it on subsequent requests, but the session data always comes back blank. Although Grav reports that the session is started, the session ID is not retained, and no custom data appears in the session array. Every request creates a new session file that only contains default system messages and no trace of my custom variable.
This indicates that, while PHP sessions work correctly in standalone tests, within Grav the session data is not being persisted. It seems that either Grav is regenerating the session on every request or is otherwise preventing custom session variables from being stored.
Has anyone encountered this behavior or have suggestions on how to resolve it?
I’m using this Twig test (session-test.html.twig):
TWIG
{%setsession=grav.session%}<p>Session started: {{session.isStarted()?'Yes':'No'}}</p>{%ifnotsession.isStarted()%}{%dosession.start()%}{%endif%}{%ifsession.get('access_granted')is notnull%}<p>Session variable exists: {{session.get('access_granted')}}</p>{%else%}{%dosession.set('access_granted', true)%}<p>Session variable set for the first time.</p>{%endif%}<pre>Session Dump: {{dump(session.all())}}</pre>
Standalone PHP tests (for sessions and cookies) work fine, but within Grav the session variable never persists and $_COOKIE remains empty.
Class Session does not have a set() and get() functions, but uses the magic functions __set() and __get().
Try {% do session.__set('access_granted', true) %}
Twig is a template engine to generate HTML. I would not use it to alter/set server data.
I would prefer to separate the responsibilities and use PHP in either the theme or a plugin to set server data and then "export" server data to Twig using $this->grav['twig']->twig_vars = ['access_granted' => true]