Cookie.php
2.7 KB
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
126
127
128
129
130
131
132
133
134
135
136
<?php
class LtCookie
{
public $configHandle;
private $secretKey;
public function __construct()
{
if (! $this->configHandle instanceof LtConfig)
{
if (class_exists("LtObjectUtil", false))
{
$this->configHandle = LtObjectUtil::singleton("LtConfig");
}
else
{
$this->configHandle = new LtConfig;
}
}
}
public function init()
{
$this->secretKey = $this->configHandle->get("cookie.secret_key");
if(empty($this->secretKey))
{
trigger_error("cookie.secret_key empty");
}
}
/**
* Decrypt the encrypted cookie
*
* @param string $encryptedText
* @return string
*/
protected function decrypt($encryptedText)
{
$key = $this->secretKey;
$cryptText = base64_decode($encryptedText);
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
$decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
return trim($decryptText);
}
/**
* Encrypt the cookie
*
* @param string $plainText
* @return string
*/
protected function encrypt($plainText)
{
$key = $this->secretKey;
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
$encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($encryptText));
}
/**
* Set cookie value to deleted with $name
*
* @param array $args
* @return boolean
*/
public function delCookie($name, $path = '/', $domain = null)
{
if (isset($_COOKIE[$name]))
{
if (is_array($_COOKIE[$name]))
{
foreach($_COOKIE[$name] as $k => $v)
{
setcookie($name . '[' . $k . ']', '', time() - 86400, $path, $domain);
}
}
else
{
setcookie($name, '', time() - 86400, $path, $domain);
}
}
}
/**
* Get cookie value with $name
*
* @param string $name
* @return mixed
*/
public function getCookie($name)
{
$ret = null;
if (isset($_COOKIE[$name]))
{
if (is_array($_COOKIE[$name]))
{
$ret = array();
foreach($_COOKIE[$name] as $k => $v)
{
$v = $this->decrypt($v);
$ret[$k] = $v;
}
}
else
{
$ret = $this->decrypt($_COOKIE[$name]);
}
}
return $ret;
}
/**
* Set cookie
*
* @param array $args
* @return boolean
*/
public function setCookie($name, $value = '', $expire = null, $path = '/', $domain = null, $secure = 0)
{
if (is_array($value))
{
foreach($value as $k => $v)
{
$v = $this->encrypt($v);
setcookie($name . '[' . $k . ']', $v, $expire, $path, $domain, $secure);
}
}
else
{
$value = $this->encrypt($value);
setcookie($name, $value, $expire, $path, $domain, $secure);
}
}
}