SafeCookie.class.php
1.62 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
<?php
class Util_Utils_SafeCookie {
private static $cookie = null;
private static function cookie() {
if(!isset($cookie)) {
self::$cookie = new Util_Cookie();
}
return self::$cookie;
}
/**
* 设置
*
* @param string $key
* @param array|string $value
* @param int $expire
* @param string $domain
* @return boolean
*/
public static function set($key, $value, $expire = 1209600, $domain = '') {
if(is_array($value)) {
$value = json_encode($value);
}
//默认整个域
if(empty($domain)) {
$domain = strstr($_SERVER['HTTP_HOST'], '.');
}
//设置时效,默认两周
return self::cookie()->setName($key)->setExpire($expire)->setDomain($domain)->setPath('/')->setValue(Util_Utils_AuthCode::encode($value, $key))->set();
}
/**
* 获取
*
* @param string $key
* @return array|string
*/
public static function get($key) {
$value = self::cookie()->get($key);
$value = Util_Utils_AuthCode::decode($value, $key);
$var = json_decode($value, true);
return empty($var)? $value: $var;
}
/**
* 清除
*
* @param string $key
* @param string $domain
* @return boolean
*/
public static function clear($key, $domain = '') {
//默认整个域
if(empty($domain)) {
$domain = strstr($_SERVER['HTTP_HOST'], '.');
}
return self::cookie()->setName($key)->setExpire(-1)->setPath('/')->setDomain($domain)->setValue('')->set();
}
}