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?
@mkglass, I cannot reproduce the issue…
Please show us your setup and code.
@pamtbaau Hi, thanks for the response.
I’ve tested in two environments:
- XAMPP setup on F:\xampp with PHP 8.2.12 (session.save_path = F:\xampp\tmp)
- Grav-only setup on C:\grav-test using C:\php 8.1 (session.save_path = c:\tmp)
My system.yaml session settings are:
session:
enabled: true
initialize: false
timeout: 1800
name: grav-site
secure: false
httponly: true
path: '/'
split: false
persistence: true
allowdata: true
I’m using this Twig test (session-test.html.twig):
{% set session = grav.session %}
<p>Session started: {{ session.isStarted() ? 'Yes' : 'No' }}</p>
{% if not session.isStarted() %}
{% do session.start() %}
{% endif %}
{% if session.get('access_granted') is not null %}
<p>Session variable exists: {{ session.get('access_granted') }}</p>
{% else %}
{% do session.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.
Thanks!
@mkglass, Please correct the formatting of both you config and code snippets using triple backticks (```).
1 Like
The magic methods worked, thank you. I’m going to work on implementing a plugin to handle my session data going forward. Thanks for your help!