session_set_save_handler

session_set_save_handler(SessionHandlerInterface $handler, bool $register_shutdown = true): bool

Custom session storage: register a SessionHandlerInterface implementation (open/close/read/write/destroy/gc) to replace file storage - the official exit hatch for Redis/DB-backed sessions.

C C23

C23
#include <stdio.h>
#include <string.h>

/* C in reverse: no session layer in stdlib - a hand-rolled id table is
   what every framework's session store boils down to */
typedef struct {
    char sid[32];
    char user[32];
    int n;
} Session;

static Session table[8] = {{0}}; /* static storage: zero-initialized */
static int count = 0;

static Session *find_session(const char *sid) {
    for (int i = 0; i < count; i++) {
        if (strcmp(table[i].sid, sid) == 0) {
            return &table[i];
        }
    }
    return NULL;
}

int main(void) {
    Session *s = find_session("demo-a44");
    if (!s) {
        s = &table[count++];
        strcpy(s->sid, "demo-a44");
    }
    strcpy(s->user, "alice");
    s->n = 42;
    Session *again = find_session("demo-a44");
    printf("user: %s n: %d\n", again->user, again->n);
    printf("sessions: %d\n", count);
    return 0;
}
Output
user: alice n: 42
sessions: 1

C++ C++26

C++26
#include <iostream>
#include <map>
#include <string>

int main() {
    // C++ in reverse: web frameworks (Drogon/Crow) own sessions; the seam is
    // a map from session id to attribute map
    std::map<std::string, std::map<std::string, std::string>> store;
    store["demo-a44"]["user"] = "alice";
    store["demo-a44"]["n"] = "42";
    std::cout << "user: " << store["demo-a44"]["user"]
              << " n: " << store["demo-a44"]["n"] << "\n";
    std::cout << "sessions: " << store.size() << "\n";
    return 0;
}
Output
user: alice n: 42
sessions: 1

C# v11.0.100

v11.0.100
using System.Collections.Generic;
using System.Text;

// C# in reverse: ASP.NET Core session state rides IDistributedCache
// (Redis/SQL Server providers) - the seam is bytes under string keys
var store = new Dictionary<string, byte[]>();
store["demo-a44:user"] = Encoding.UTF8.GetBytes("alice");
store["demo-a44:n"] = Encoding.UTF8.GetBytes("42");
Console.WriteLine($"user: {Encoding.UTF8.GetString(store["demo-a44:user"])}");
Console.WriteLine($"n: {Encoding.UTF8.GetString(store["demo-a44:n"])}");
Console.WriteLine($"keys: {store.Count}");
Output
user: alice
n: 42
keys: 2

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sync"
)

// Go in reverse: no stdlib session store - managers hand-roll a
// mutex-protected map (gorilla/sessions wraps exactly this shape)
type SessionManager struct {
	mu    sync.Mutex
	store map[string]map[string]any
}

func NewSessionManager() *SessionManager {
	return &SessionManager{store: map[string]map[string]any{}}
}

func (m *SessionManager) Get(sid string) map[string]any {
	m.mu.Lock()
	defer m.mu.Unlock()
	data, ok := m.store[sid]
	if !ok {
		data = map[string]any{}
		m.store[sid] = data
	}
	return data
}

func (m *SessionManager) Has(sid string) bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	_, ok := m.store[sid]
	return ok
}

func main() {
	m := NewSessionManager()
	sess := m.Get("demo-a44")
	sess["user"] = "alice"
	sess["n"] = 42
	fmt.Println("user:", sess["user"], "n:", sess["n"])
	fmt.Println("persisted:", m.Has("demo-a44"))
	fmt.Println("reload user:", m.Get("demo-a44")["user"])
}
Output
user: alice n: 42
persisted: true
reload user: alice

Java v27.0.1

v27.0.1
import java.util.HashMap;
import java.util.Map;

public class Main {
    // Java in reverse: HttpSession comes from the servlet container and
    // Spring Session swaps the store behind it - the seam is a plain Map here
    static class MemorySessions {
        private final Map<String, Map<String, Object>> store = new HashMap<>();

        Map<String, Object> get(String sid) {
            return store.computeIfAbsent(sid, k -> new HashMap<>());
        }

        boolean has(String sid) {
            return store.containsKey(sid);
        }
    }

    public static void main(String[] args) {
        MemorySessions sessions = new MemorySessions();
        Map<String, Object> sess = sessions.get("demo-a44");
        sess.put("user", "alice");
        sess.put("n", 42);
        System.out.println("user: " + sess.get("user") + " n: " + sess.get("n"));
        System.out.println("persisted: " + sessions.has("demo-a44"));
    }
}
Output
user: alice n: 42
persisted: true

JavaScript v26.13.1

v26.13.1
// JS in reverse: express-session takes a store object (connect-redis etc.)
// with get/set/destroy - here the in-memory store to make the seam visible
class MemoryStore {
  #map = new Map();
  get(sid) { return this.#map.get(sid) ?? null; }
  set(sid, blob) { this.#map.set(sid, blob); }
  destroy(sid) { this.#map.delete(sid); }
  get count() { return this.#map.size; }
}
const store = new MemoryStore();
store.set("demo-a44", JSON.stringify({ user: "alice", n: 42 }));
const restored = JSON.parse(store.get("demo-a44"));
console.log("user:", restored.user, "n:", restored.n);
console.log("sessions:", store.count);
store.destroy("demo-a44");
console.log("after destroy:", store.count);
Output
user: alice n: 42
sessions: 1
after destroy: 0

PHP v8.6.0

v8.6.0
// session_set_save_handler: swap the storage behind $_SESSION (files -> Redis/DB)
// by registering a SessionHandlerInterface implementation; in-memory store here
class MemorySessionHandler implements SessionHandlerInterface, SessionIdInterface, SessionUpdateTimestampHandlerInterface
{
    public static array $store = [];
    public function open(string $path, string $name): bool { return true; }
    public function close(): bool { return true; }
    public function read(string $id): string { return self::$store[$id] ?? ""; }
    public function write(string $id, string $data): bool { self::$store[$id] = $data; return true; }
    public function destroy(string $id): bool { unset(self::$store[$id]); return true; }
    public function gc(int $maxLifetime): int { return 0; }
    public function create_sid(): string { return "sid-" . bin2hex(random_bytes(8)); }
    public function validateId(string $id): bool { return preg_match('/^[A-Za-z0-9,-]{1,128}$/', $id) === 1; }
    public function updateTimestamp(string $id, string $data): bool { self::$store[$id] = $data; return true; }
}
// Keep every echo until the session work is done: output closes the header phase
session_set_save_handler(new MemorySessionHandler(), true);
ini_set("session.use_cookies", "0"); // cookie-free CLI demo
session_id("demo-a44");
session_start(); // fires open() -> read()
$_SESSION["user"] = "alice";
$_SESSION["n"] = 42;
session_write_close(); // fires write(): the blob lands in the memory store
$blobBytes = strlen(MemorySessionHandler::$store["demo-a44"]);
session_start(); // reload: fires read() and repopulates $_SESSION
$reloadedUser = $_SESSION["user"] ?? "(missing)";
$reloadedN = $_SESSION["n"] ?? "(missing)";
$sessions = count(MemorySessionHandler::$store);
session_write_close();
echo "blob bytes: $blobBytes\n";
echo "reloaded user: $reloadedUser\n";
echo "reloaded n: $reloadedN\n";
echo "sessions in store: $sessions\n";
Output
blob bytes: 24
reloaded user: alice
reloaded n: 42
sessions in store: 1

Python v3.15.2

v3.15.2
# Python in reverse: session storage is framework land (Flask/Django session
# backends swap in Redis/DB); the storage seam itself is just three verbs
class MemoryStore:
    def __init__(self):
        self.data = {}

    def read(self, sid):
        return self.data.get(sid, "")

    def write(self, sid, blob):
        self.data[sid] = blob
        return True

    def destroy(self, sid):
        self.data.pop(sid, None)
        return True

store = MemoryStore()
store.write("demo-a44", "user|s:5:alice;n|i:42")
restored = store.read("demo-a44")
print("restored:", restored)
print("sessions:", len(store.data))
store.destroy("demo-a44")
print("after destroy:", len(store.data))
Output
restored: user|s:5:alice;n|i:42
sessions: 1
after destroy: 0

Rust v1.99.1

v1.99.1
// Rust in reverse: session frameworks (axum/actix-session) own the storage;
// underneath it is a plain map from id to payload
use std::collections::HashMap;

fn main() {
    let mut store: HashMap<String, Vec<(String, String)>> = HashMap::new();
    store.insert(
        "demo-a44".to_string(),
        vec![
            ("user".to_string(), "alice".to_string()),
            ("n".to_string(), "42".to_string()),
        ],
    );
    let sess = &store["demo-a44"];
    let user = sess.iter().find(|(k, _)| k == "user").map(|(_, v)| v.as_str()).unwrap();
    let n = sess.iter().find(|(k, _)| k == "n").map(|(_, v)| v.as_str()).unwrap();
    println!("user: {} n: {}", user, n);
    println!("sessions: {}", store.len());
}
Output
user: alice n: 42
sessions: 1

TypeScript v26.13.1

v26.13.1
// TS in reverse: the store contract gets types - a SessionData shape
// behind get/set/destroy mirrors what express-session expects
interface SessionData {
  user: string;
  n: number;
}
class MemoryStore {
  #map = new Map<string, SessionData>();
  get(sid: string): SessionData | null { return this.#map.get(sid) ?? null; }
  set(sid: string, data: SessionData): void { this.#map.set(sid, data); }
  destroy(sid: string): void { this.#map.delete(sid); }
  get count(): number { return this.#map.size; }
}
const store = new MemoryStore();
store.set("demo-a44", { user: "alice", n: 42 });
const restored = store.get("demo-a44");
console.log("user:", restored?.user, "n:", restored?.n);
console.log("sessions:", store.count);
store.destroy("demo-a44");
console.log("after destroy:", store.count);
Output
user: alice n: 42
sessions: 1
after destroy: 0

Language differences

C: no session concept - a web-server module or a hand-rolled id->payload table (shown) is the substrate every framework session store reduces to.

C++: same as C - sessions belong to the web-framework layer (Drogon's Session interface, Crow middleware); rolling your own is a locked map.

C#: ASP.NET Core session state rides IDistributedCache (Redis/SQL Server providers) - distributed sessions are a built-in story, wired with AddSession + UseSession.

Go: nothing in the standard library - gorilla/sessions is the de facto standard (CookieStore/FilesystemStore/Redis backends); a hand-rolled manager is a mutex + map (shown).

Java: HttpSession is supplied by the servlet container (Tomcat/Jetty), and Spring Session swaps the backing store to Redis/JDBC through a filter - the model case of decoupling app code from storage.

JavaScript: express-session takes a store object (get/set/destroy callbacks); connect-redis and connect-mongo are the ready backends, and the default MemoryStore is dev-only (the example hand-writes the same shape).

PHP: session_set_save_handler is the ONLY port for swapping session storage: the OO signature session_set_save_handler($handler, true) takes a SessionHandlerInterface implementation (open/close/read/write/destroy/gc), optionally plus SessionIdInterface (create_sid) and SessionUpdateTimestampHandlerInterface (validateId/updateTimestamp). Teaching points: the multi-argument callable signature is deprecated since 8.4 (migrate to the object form); write/close run after object destruction (the true second argument registering a shutdown handler is the official fix); read must return the stored string or "" (only false means failure); this is the official exit for the real-web Redis/DB session scenario (the example closes register->write->read with an in-memory table).

Python: sessions live in the framework - Flask's session object (signed secure cookie), the Flask-Session extension (Redis/file backends), and Django's SESSION_ENGINE setting are the official swap points.

Rust: axum/actix-session ship in-memory sessions, Redis backends come from crates (actix-redis and friends) - the "storage seam" is just an id->payload map (shown).

TypeScript: the same JS store contract; TS's value is typing the store interface (get/set/destroy signatures plus a SessionData shape, shown).