-
-
Notifications
You must be signed in to change notification settings - Fork 1
Redis session storage
RedisHandler stores session data in Redis-compatible storage.
This is useful when an application runs on more than one server, or when the server filesystem is temporary. Redis and Valkey are common choices for this kind of shared session storage.
Important
RedisHandler requires the phpredis extension. The package suggests ext-redis, but Composer cannot install PHP extensions for us.
use GT\Session\RedisHandler;
use GT\Session\Session;
$session = new Session(new RedisHandler(), [
"name" => "GT",
"save_path" => "redis://localhost:6379/0",
]);The save path is a DSN. Session recognises DSN-style save paths and leaves them unchanged.
redis://localhost:6379
redis://:secret@localhost:6379/0
redis://default:secret@redis.internal:6379/2
rediss://default:secret@redis.internal:25061/0
The path part selects the Redis database. If no database is supplied, database 0 is used.
If the DSN contains both a username and password, the handler passes both to Redis::auth().
redis://default:secret@redis.internal:6379/0
If the DSN contains only a password, the handler authenticates with just the password.
redis://:secret@redis.internal:6379/0
Supported query parameters are:
prefixttltimeoutread_timeoutpersistentpersistent_idverify_peerverify_peer_name
Example:
rediss://default:secret@example-redis.internal:25061/0?prefix=GT:&ttl=1440&timeout=1.5&read_timeout=2.5&persistent=1
By default, Redis keys are prefixed with the session name followed by a colon.
For a session named GT, the key for session ID abc123 is:
GT:abc123
Set the prefix query parameter to choose a different prefix:
redis://localhost:6379/0?prefix=app-session:
The ttl query parameter controls the Redis expiry time in seconds.
redis://localhost:6379/0?ttl=3600
If no TTL is supplied, the handler uses PHP's session.gc_maxlifetime value.
When TTL is greater than zero, writes use setEx(). Otherwise, writes use set().
Use rediss:// or tls:// for TLS connections.
rediss://default:secret@redis.internal:25061/0
For local testing against a TLS endpoint with self-signed certificates, verification can be disabled:
rediss://default:secret@redis.internal:25061/0?verify_peer=0&verify_peer_name=0
Only disable verification when we understand the security trade-off.
In WebEngine, the same handler can be configured in config.ini:
[session]
handler=GT\Session\RedisHandler
path=rediss://default:secret@example-redis.internal:25061/0?prefix=GT:&ttl=1440
name=GT
use_cookies=trueNote
WebEngine passes [session] path to this library as save_path. For Redis, that value should be the Redis DSN rather than a filesystem path.
Next, learn how to show one-request notices in Flash messages.
phpgt/session is a separately maintained component of PHP.GT/WebEngine.