-
Notifications
You must be signed in to change notification settings - Fork 0
/
Session.php
110 lines (98 loc) · 2.44 KB
/
Session.php
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
namespace alvin\phpmvc;
/**
* Class for handling php sessions
*/
class Session {
/**
* Name of the object inside $_SESSION to store the flash messages in
* @var string
*/
private const FLASH_KEY = 'flash';
/**
* Creates a Session object.
*
* Sets session lifetime,cookie lifetime and csrf token
*
* @param integer $lifetime session and cookie lifetime
* @param integer $httpOnly httpOnly cookies or not
*/
public function __construct(int $lifetime = 172800, int $httpOnly = 1) {
ini_set('session.gc_maxlifetime', $lifetime);
session_set_cookie_params($lifetime);
ini_set('session.cookie_httponly', $httpOnly);
session_start();
$flashMessages = $_SESSION[self::FLASH_KEY] ?? [];
foreach ($flashMessages as $key => &$flashMessage) {
$flashMessage['remove'] = true;
}
$_SESSION[self::FLASH_KEY] = $flashMessages;
$csrfToken = bin2hex(random_bytes(24));
if (!isset($_SESSION['csrfToken']) || !isset($_COOKIE['XSRF_TOKEN'])) {
$_SESSION['csrfToken'] = $csrfToken;
setcookie('XSRF_TOKEN', $csrfToken, ["samesite" => "strict", "expires" => time() + 172800, "path" => "/"]);
}
}
/**
* Sets a session
*
* @param string $key Session key
* @param mixed $value Session value
* @return void
*/
public function setSession($key, $value) {
$_SESSION[$key] = $value;
}
/**
* Returns a session value
*
* @param string $key session key
* @return mixed|false
*/
public function getSession($key) {
return $_SESSION[$key] ?? false;
}
/**
* Regenerates and removes a session
* @return void
*/
public function removeSession() {
session_regenerate_id(true);
session_unset();
session_destroy();
}
/**
* Set a flash message
*
* @param string $key flash message key
* @param string $value flash message value
* @return void
*/
public function flash(string $key, string $value) {
$_SESSION[self::FLASH_KEY][$key] = [
'remove' => false,
'value' => $value,
];
}
/**
* Removes a flash message
* @return void
*/
public function removeFlashMessages() {
$flashMessages = $_SESSION[self::FLASH_KEY] ?? [];
foreach ($flashMessages as $key => $flashMessage) {
if ($flashMessage['remove']) {
unset($flashMessages[$key]);
}
}
$_SESSION[self::FLASH_KEY] = $flashMessages;
}
/**
* Destroys a session object.
*
* Uses removeFlashMessages to remove a flash message on object destruction
*/
public function __destruct() {
$this->removeFlashMessages();
}
}