1 | <?php declare(strict_types=1); |
||
5 | final class SessionManager |
||
6 | { |
||
7 | const IP_REGEX = '/(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/'; |
||
8 | |||
9 | /** |
||
10 | * As this is a singleton, construction and clone are disabled |
||
11 | * use SessionManager::getInstance() if you need the instance |
||
12 | */ |
||
13 | private function __construct(){} |
||
14 | |||
15 | private function __clone(){} |
||
16 | |||
17 | /** |
||
18 | * @return SessionManager |
||
19 | */ |
||
20 | public static function getInstance(): SessionManager |
||
30 | |||
31 | /** |
||
32 | * Creates a secure session |
||
33 | * |
||
34 | * @param string $name |
||
35 | * @param int $lifetime |
||
36 | * @param string $path |
||
37 | * @param string $domain |
||
38 | * @param bool|null $secure |
||
39 | */ |
||
40 | public static function sessionStart(string $name, int $lifetime = 0, string $path = '/', string $domain = '', ?bool $secure = null): void |
||
78 | |||
79 | /** |
||
80 | * @return bool |
||
81 | */ |
||
82 | private function shouldRandomlyRegenerate(): bool |
||
86 | |||
87 | |||
88 | /** |
||
89 | * Checks session IP and user agent are still the same |
||
90 | * @return bool |
||
91 | */ |
||
92 | private function preventHijacking(): bool |
||
111 | |||
112 | /** |
||
113 | * If a site goes through the likes of Cloudflare, the last part of the IP might change |
||
114 | * So we replace it with an x. |
||
115 | * |
||
116 | * @return string |
||
117 | */ |
||
118 | private function getIpAddress(): string |
||
124 | |||
125 | /** |
||
126 | * Creates a fresh session Id to make it harder to hack |
||
127 | * If the site is very slow in parts increase the expiry time |
||
128 | * 10 seconds is a good default which allows ajax calls to work |
||
129 | * without losing the session |
||
130 | */ |
||
131 | private function regenerateSession() |
||
157 | |||
158 | /** |
||
159 | * Checks whether the session has expired or not |
||
160 | * @return bool |
||
161 | */ |
||
162 | private function validateSession() |
||
174 | |||
175 | /** |
||
176 | * Resets the session |
||
177 | */ |
||
178 | public static function destroySession() |
||
188 | |||
189 | /** |
||
190 | * @param string $key |
||
191 | * @param mixed $val |
||
192 | */ |
||
193 | public static function set(string $key, $val): void |
||
197 | |||
198 | /** |
||
199 | * @param $key |
||
200 | * @return null |
||
201 | */ |
||
202 | public static function get(string $key) |
||
206 | |||
207 | /** |
||
208 | * @param string $key |
||
209 | * @return bool |
||
210 | */ |
||
211 | public static function has(string $key): bool |
||
215 | |||
216 | /** |
||
217 | * @param $key |
||
218 | * @param $val |
||
219 | */ |
||
220 | public static function unset(string $key): void |
||
224 | |||
225 | /** |
||
226 | * @param $key |
||
227 | * @param $val |
||
228 | * @deprecated use unset |
||
229 | */ |
||
230 | public static function destroy(string $key): void |
||
234 | } |
||
235 |