diff options
| author | Connor Thomson <blumatrikz@gmail.com> | 2026-09-20 18:59:16 -0700 |
|---|---|---|
| committer | Connor Thomson <blumatrikz@gmail.com> | 2026-09-20 18:59:48 -0700 |
| commit | 81c04315ee022a044c8d22ae7a9bbe065e21f2df (patch) | |
| tree | bd3fed9001a07917c0f45b6f51e62fffc1ea2c97 /php/session.php | |
| parent | 09cda8862f59f25918c64477d829e46acfc676cb (diff) | |
Add signin
Diffstat (limited to 'php/session.php')
| -rwxr-xr-x | php/session.php | 71 |
1 files changed, 64 insertions, 7 deletions
diff --git a/php/session.php b/php/session.php index 7895dfb..acb2df3 100755 --- a/php/session.php +++ b/php/session.php @@ -17,20 +17,63 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -function start_session(): void { - if (session_status() === PHP_SESSION_ACTIVE) { - return; - } +const SESSION_LIFETIME = 60 * 60 * 24 * 365; - session_set_cookie_params([ - 'lifetime' => 0, +function session_cookie(int $lifetime): array { + return [ + 'lifetime' => $lifetime, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' - ]); + ]; +} + +function has_session(): bool { + if (session_status() === PHP_SESSION_ACTIVE) { + return true; + } + + return isset($_COOKIE[session_name()]); +} + +function start_session(): void { + if (session_status() === PHP_SESSION_ACTIVE) { + return; + } + + ini_set('session.gc_maxlifetime', (string)SESSION_LIFETIME); + + session_set_cookie_params(session_cookie(0)); session_start(); + + if (!empty($_SESSION['remember'])) { + remember_session(); + } +} + +function remember_session(): void { + $parameters = session_cookie(SESSION_LIFETIME); + $parameters['expires'] = time() + $parameters['lifetime']; + + unset($parameters['lifetime']); + + setcookie(session_name(), session_id(), $parameters); +} + +function sign_in(int $user_id, string $username, bool $remember): void { + start_session(); + + session_regenerate_id(true); + + $_SESSION['user_id'] = $user_id; + $_SESSION['username'] = $username; + $_SESSION['remember'] = $remember; + + if ($remember) { + remember_session(); + } } function set_user_id(int $user_id): void { @@ -42,9 +85,23 @@ function set_user_id(int $user_id): void { } function get_user_id(): ?int { + if (!has_session()) { + return null; + } + start_session(); return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null; } +function get_username(): ?string { + if (!has_session()) { + return null; + } + + start_session(); + + return isset($_SESSION['username']) ? (string)$_SESSION['username'] : null; +} + ?> |
