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 |
||
110 | |||
111 | /** |
||
112 | * If a site goes through the likes of Cloudflare, the last part of the IP might change |
||
113 | * So we replace it with an x. |
||
114 | * |
||
115 | * @return string |
||
116 | */ |
||
117 | private function getIpAddress(): string |
||
121 | |||
122 | /** |
||
123 | * Creates a fresh session Id to make it harder to hack |
||
124 | * If the site is very slow in parts increase the expiry time |
||
125 | * 10 seconds is a good default which allows ajax calls to work |
||
126 | * without losing the session |
||
127 | */ |
||
128 | private function regenerateSession() |
||
154 | |||
155 | /** |
||
156 | * Checks whether the session has expired or not |
||
157 | * @return bool |
||
158 | */ |
||
159 | private function validateSession() |
||
171 | |||
172 | /** |
||
173 | * Resets the session |
||
174 | */ |
||
175 | public static function destroySession() |
||
185 | |||
186 | /** |
||
187 | * @param string $key |
||
188 | * @param mixed $val |
||
189 | */ |
||
190 | public static function set(string $key, $val): void |
||
194 | |||
195 | /** |
||
196 | * @param $key |
||
197 | * @return null |
||
198 | */ |
||
199 | public static function get(string $key) |
||
203 | |||
204 | /** |
||
205 | * @param $key |
||
206 | * @param $val |
||
207 | */ |
||
208 | public static function destroy(string $key): void |
||
212 | } |
||
213 |