innmind/http-session

4.1.0 2025-07-30 15:32 UTC

README

Build Status codecov Type Coverage

Library to manage session for http requests.

The goal is to break the paradigm of considering the request and response as a global environment. Request and response should be delt as transiting data. The session for a request should obey this principle as well, thus the signature Manager::start(ServerRequest): Maybe<Session>.

Installation

composer require innmind/http-session

Usage

use Innmind\HttpSession\Manager\Native;
use Innmind\Http\{
    Response,
    Response\StatusCode,
    ServerRequest,
    Headers,
    Header\SetCookie,
    Header\SetCookie\Directive,
    Header\SetCookie\Domain,
};

$manager = Native::of();
$request = /* an instance of ServerRequest */

$session = $manager->start($request)->match(
    static fn($session) => $session,
    static fn() => throw new \RuntimeException('Unable to start the exception'),
);
// inject some data in the session
$manager->save($session);

$response = Response::of(
    StatusCode::ok,
    $request->protocolVersion(),
    Headers::of(
        SetCookie::of(
            $session->name()->toString(),
            $session->id()->toString(),
            Directive::httpOnly,
            Domain::of($request->url()->authority()->host()),
        ),
    ),
);
// send the response

Note

You should take a look at innmind/http-server in order to know how to have access to an instance of ServerRequest and send the Response.