Last active
May 12, 2021 15:00
-
-
Save iluuu1994/ebe51d10b02a6ae30cdd639b769cf95e to your computer and use it in GitHub Desktop.
Vanilla sessions with RoadRunner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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