Skip to content

Constructing a Session

Greg Bowler edited this page Apr 23, 2026 · 1 revision

Session is the main entry point to the library.

The constructor accepts:

  1. a PHP SessionHandlerInterface
  2. an optional configuration array
  3. an optional session ID
use GT\Session\FileHandler;
use GT\Session\Session;

$session = new Session(
	new FileHandler(),
	[
		"name" => "GT",
		"save_path" => "phpgt/session",
	]
);

Using SessionSetup

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.

Configuration keys

The constructor passes session options through to session_start().

Common keys are:

  • name
  • save_path
  • use_only_cookies
  • use_cookies
  • use_trans_sid
  • cookie_lifetime
  • cookie_path
  • cookie_domain
  • cookie_secure
  • cookie_httponly
  • cookie_samesite
  • use_strict_mode

The library also forces PHP's session serialiser to php_serialize, because the stored data is a serialised SessionStore object.

Defaults

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.

Save paths

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",
]);

Supplying a session ID

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.

Clone this wiki locally