-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.php
More file actions
43 lines (37 loc) · 785 Bytes
/
auth.php
File metadata and controls
43 lines (37 loc) · 785 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
declare(strict_types=1);
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/helpers.php';
/**
* Returns currently logged-in user (or null).
*/
function current_user(): ?array
{
if (empty($_SESSION['user_id'])) {
return null;
}
$stmt = db()->prepare('SELECT id, email FROM users WHERE id = ? LIMIT 1');
$stmt->execute([ (int)$_SESSION['user_id'] ]);
$user = $stmt->fetch();
return $user ?: null;
}
/**
* Enforce login.
*/
function require_login(): void
{
if (empty($_SESSION['user_id'])) {
redirect('/login.php');
}
}
/**
* Logout helper (optional).
*/
function logout(): void
{
$_SESSION = [];
if (session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
}
redirect('/login.php');
}