Skip to content
docs.
WORKSPACE

Your documentation

Explore the project catalog
Localzet ServerАсинхронный PHP-серверTriangleФреймворк и компоненты✓MIX IDИдентификация и интеграцииHack APIПубличные API хакатонаACNПроект и компонентыUserlay / UserNetПроект и компонентыAxiomПроект и компонентыМесседжинг через почтуПроект и компонентыLWT / JWT / JOSEПроект и компонентыФинансовая аналитика KimaiПроект и компонентыМультипарадигмальная БДПроект и компонентыZorin PlatformПроект и компонентыZorin TrustПроект и компонентыFloraScope / VegwatchПроект и компонентыaegis-qДокументация проектаaevumdbДокументация проектаauditДокументация проектаauto-invest-managerАвтотрейдерcaine-companionДокументация проектаcertbot-cloudflareДокументация проектаClusterLocalzet Server / ClustercmdveilДокументация проектаConsolePHP CLICronБиблиотеки Localzet Serverdata-connectorДокументация проектаdevice-controlDevice Controlenn-projectДокументация проектаEventsБиблиотеки Localzet ServerflowsintДокументация проектаforgeДокументация проектаHttpClientБиблиотеки Localzet ServerinterpreterСобственный языкinvariaДокументация проектаkeynotesДокументация проектаknotrouteKnotroutelaravel-personal-analyticsДокументация проектаlocalzet-osДокументация проектаmeridianДокументация проектаMQTTБиблиотеки Localzet Servernano-kernelСобственная ОСNoterДокументация проектаpersonal-analyticsДокументация проектаProxyБиблиотеки Localzet ServerPSRБиблиотеки Localzet ServerPSR-7Библиотеки Localzet Serverrschs-monitorДокументация проектаsemsealДокументация проектаshardsealДокументация проектаSocketIOБиблиотеки Localzet ServerSOCKS5Библиотеки Localzet Serverstandalone-analyticsДокументация проектаstatic-php-cliДокументация проектаStorageБиблиотеки Localzet ServersutureДокументация проектаtempoweaveДокументация проектаttsСинтез речиTunnelБиблиотеки Localzet Serverui-kitUI KitvesperДокументация проектаWebAnalyzerWebAnalyzerzorin-access-brokerДокументация проектаzorin-authority-brokerДокументация проектаzorin-authority-sdk-phpДокументация проектаzorin-authority-sdk-pythonДокументация проектаzorin-authority-sdk-tsДокументация проектаzorin-client-intelДокументация проектаzorin-device-core-aospДокументация проектаzorin-host-agentДокументация проектаzorin-native-labДокументация проектаzorin-nodeДокументация проектаzorin-opsДокументация проектаdonstu-python-sdkДокументация проектаfloortraceFloortraceserver-rsLocalzet Server / Cluster
Catalog
Documentation/Triangle

Session

Triangle Session configures Localzet Server sessions for a Triangle application and provides the session() helper. Each HTTP request owns its session object; handler and cookie settings are shared by the worker. This is separate from PHP session_start.

Окно терминала
composer require triangle/session

The package requires PHP ^8.1 and triangle/engine ^8.1. This Engine branch requires localzet/server ^4. Keep the application lockfile: Server 7.x behavior does not establish the behavior of this dependency chain.

$session = $request->session();
$session->put('display_name', 'Reader');
$name = $session->get('display_name', 'Guest');
$session->forget('display_name');

The helper resolves the current request:

session(['preferences' => ['language' => 'en']]);
$language = session('preferences.language', 'ru');
$session = session();

An array writes fields and returns null. No argument returns the session object. A string reads a field; the second argument is a fallback, not a value to write. Dotted reads use isset, so a nested null produces the fallback. Writing ['preferences.language' => 'en'] creates a literal key, not a nested structure.

Use the helper inside an active request. Do not retain its session object in a shared service or use it for another request.

Session.php selects file, redis, redis_cluster or mongo through SESSION_TYPE. An unknown type causes a match error; there is no fallback handler. Keep type, handler and the corresponding config entry consistent.

File defaults to runtime/sessions. File/Redis/RedisCluster classes inherit Server handlers without overriding behavior. Redis configuration includes connection, authentication, database, timeout and key prefix; cluster uses a node list. Mongo accepts URL or host/port, database, collection and driver options. MongoDB Client and the mongodb extension must be installed by the application; the component does not require them directly in Composer.

Defaults shipped by the component: data lifetime 7 days, cookie lifetime 365 days, name PHPSID, path /, HttpOnly true, Secure false and empty SameSite. Cookie lifetime does not extend stored data lifetime.

Set Secure for HTTPS and choose SameSite/domain for the actual application flow. CSRF protection and session-ID rotation after sign-in or privilege elevation remain application responsibilities.

Bootstrap applies only truthy settings. False, zero and empty strings do not reset previously assigned static values; for example http_only=false or cookie_lifetime=0 can be ignored. Verify actual Set-Cookie attributes rather than assuming every config value was applied.

A stored session is a serialized snapshot. Atomic file replacement does not make concurrent read-modify-write operations transactional: requests can overwrite each other’s updates. Do not use sessions as durable queues or accounting records.

Server 4.5.1 save ignores a false return from handler write. A completed request is not proof that persistence succeeded. Use separate durable storage and failure handling for critical business data.

Read returns the entire document, including _id and updated_at, as session data and does not reject an expired document itself. Gc constructs UTCDateTime from time() - $maxLifetime * 1000, mixing seconds and milliseconds; it does not implement the intended expiry interval. Selecting Mongo does not create a TTL index. Use another handler or implement and verify expiry separately before relying on this storage policy.

session(mixed $key = null, mixed $default = null): mixed is declared only if no function named session exists. A conflicting library may therefore supply a different helper; $request->session() is unambiguous.

No key returns the current session; an array calls put and returns null; a string calls get or traverses dotted fields. Dot detection uses strpos as a condition, so a leading dot is not treated as a path. Nested writes and deletion are not separate helper operations.

Triangle\Session\Bootstrap::start(?localzet\Server $server = null): void returns immediately for null. Otherwise it sets handlerClass from session.handler and session.config.{type}, then maps truthy settings to existing Session static properties:

ConfigSession property
auto_update_timestampautoUpdateTimestamp
cookie_lifetimecookieLifetime
gc_probabilitygcProbability
cookie_pathcookiePath
http_onlyhttpOnly
same_sitesameSite
lifetimelifetime
domaindomain
securesecure
session_namename

This is worker configuration, not per-user configuration. The component does not validate a complete settings schema or reset ignored values.

FileSessionHandler, RedisSessionHandler and RedisClusterSessionHandler inherit the corresponding Server classes. MongoSessionHandler implements open, close, read, write, updateTimestamp, destroy and gc. Write uses replaceOne with upsert and refreshes updated_at. Driver exceptions propagate. Its unserialize input is the internal session-handler format, not an endpoint for user-supplied serialized objects.

Install copies the bundled session.php only when the target is absent. Existing application configuration is not upgraded automatically.