-
-
Notifications
You must be signed in to change notification settings - Fork 1
Constructing a Session
Session is the main entry point to the library.
The constructor accepts:
- a PHP
SessionHandlerInterface - an optional configuration array
- an optional session ID
use GT\Session\FileHandler;
use GT\Session\Session;
$session = new Session(
new FileHandler(),
[
"name" => "GT",
"save_path" => "phpgt/session",
]
);SessionSetup is a small helper for creating and attaching a handler class by name.
use GT\Session\FileHandler;
use GT\Session\Session;
use GT\Session\SessionSetup;
$setup = new SessionSetup();
$handler = $setup->attachHandler(FileHandler::class);
$session = new Session($handler, [
"name" => "GT",
"save_path" => "phpgt/session",
]);If the handler class is not PHP's built-in SessionHandler, SessionSetup calls session_set_save_handler() before the session starts.
The constructor passes session options through to session_start().
Common keys are:
namesave_pathuse_only_cookiesuse_cookiesuse_trans_sidcookie_lifetimecookie_pathcookie_domaincookie_securecookie_httponlycookie_samesiteuse_strict_mode
The library also forces PHP's session serialiser to php_serialize, because the stored data is a serialised SessionStore object.
When a config value is not supplied, Session uses these defaults:
- session name:
PHPSESSID - save path:
/tmp - cookie lifetime:
0 - cookie path:
/ - cookie domain: empty string
- secure cookie:
true - HTTP-only cookie:
true - SameSite policy:
Lax - strict mode:
true - cookies only:
true - trans SID:
false
cookie_lifetime of 0 means the browser treats the cookie as a session cookie, normally clearing it when the browser session ends.
The save_path can be a filesystem path or a DSN.
Filesystem paths are normalised to the operating system's directory separator. Relative paths are placed under sys_get_temp_dir().
use GT\Session\FileHandler;
$session = new Session(new FileHandler(), [
"save_path" => "phpgt/session",
]);DSN-style save paths are left unchanged, so they can be passed to handlers such as RedisHandler.
use GT\Session\RedisHandler;
$session = new Session(new RedisHandler(), [
"save_path" => "rediss://default:secret@example.internal:25061/0",
]);The third constructor argument can be used when the caller already knows the session ID.
$session = new Session($handler, $config, $sessionIdFromCookie);If no ID is supplied, the library asks PHP for the current session_id(). If PHP has not created one yet, it calls session_create_id().
Note
WebEngine reads the configured session name, handler and path from config.ini, finds the current cookie value, attaches the handler, and then constructs Session for the request.
Next, learn how to organise data in Session stores and namespaces.
phpgt/session is a separately maintained component of PHP.GT/WebEngine.