-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathSessionManager.php
125 lines (102 loc) · 2.99 KB
/
SessionManager.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
class SessionManager
{
private static $cookieName = '';
private static $expires = 86400;
private static $path = '/';
private static $domain = null;
private static $secureOnly = false;
public static function setupParameters($name, $expires = 86400, $path = '/', $domain = null, $isSecure = false)
{
self::$cookieName = $name . '_SB';
self::$expires = $expires;
self::$path = $path;
self::$domain = $domain;
self::$secureOnly = $isSecure;
session_name(self::$cookieName);
$sessionId = $_COOKIE[self::$cookieName] ?: '';
if (!empty($sessionId))
session_id($sessionId);
session_id();
}
public static function startSession()
{
session_start();
self::setCookie();
if (self::ValidateSession())
{
if (!self::PreventHijacking())
{
$_SESSION = [];
self::regenerateSession();
$_SESSION = [
'user_agent' => hash('sha256', $_SERVER['HTTP_USER_AGENT']),
'expires' => time() + self::$expires
];
} else if ((rand(1, 100) <= 10) && !isset($_POST['xajax']))
{
self::regenerateSession();
}
}
}
public static function checkSession()
{
if (!isset($_SESSION['user_agent']))
return false;
if (!self::validateSession() || !self::preventHijacking())
{
session_destroy();
session_start();
return false;
}
return true;
}
public static function closeWrite()
{
@session_write_close();
}
protected static function preventHijacking()
{
if (!isset($_SESSION['user_agent']))
return false;
if ($_SESSION['user_agent'] !== hash('sha256', $_SERVER['HTTP_USER_AGENT']))
return false;
return true;
}
protected static function regenerateSession()
{
$_SESSION['expires'] = time() + 10;
session_regenerate_id(false);
$newSession = session_id();
self::setCookie();
self::closeWrite();
session_id($newSession);
session_start();
unset($_SESSION['expires']);
}
protected static function validateSession()
{
return (
!isset($_SESSION['expires']) ||
$_SESSION['expires'] >= time()
);
}
/**
* @section Session Name
*/
public static function getSessionName($domain)
{
if (defined('SB_SESSION'))
{
$session = constant('SB_SESSION');
if (!empty($session))
return $session;
}
return substr(md5($domain ?: $_SERVER['SERVER_NAME']), 0, 8);
}
public static function setCookie()
{
setcookie(self::$cookieName, session_id(), time() + self::$expires,
self::$path, self::$domain, self::$secureOnly, true);
}
}