Skip to content

Instantly share code, notes, and snippets.

@iluuu1994
Last active May 12, 2021 15:00
Show Gist options
  • Select an option

  • Save iluuu1994/ebe51d10b02a6ae30cdd639b769cf95e to your computer and use it in GitHub Desktop.

Select an option

Save iluuu1994/ebe51d10b02a6ae30cdd639b769cf95e to your computer and use it in GitHub Desktop.
Vanilla sessions with RoadRunner
<?php
class SessionService
{
public const SESSION_NAME = 'SESSIONCOOKIENAME';
public function start(HttpRequest $request): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
throw new \RuntimeException('Session is already active');
}
$sessionId = $request->cookies->get(self::SESSION_NAME);
if ($sessionId === null) {
$sessionId = session_create_id();
}
session_id($sessionId);
if (!session_start()) {
throw new \RuntimeException('Failed to start the session');
}
// Remove the cookie that gets automatically added. We add the cookie to the Response object ourselves.
header_remove('Set-Cookie');
}
public function save(): void
{
if (session_status() !== PHP_SESSION_ACTIVE) {
return;
}
if (!session_write_close()) {
throw new \RuntimeException('Failed to save session');
}
$_SESSION = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment