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
<?php
class Cookie
{
	private static $_salt = '1410fa00-f8cb-11de-8a39-0800200c9a66';

	public static function set($key, $value)
	{
		self::assertSecured($_COOKIE);
		
		$arr = $_COOKIE; $arr[$key] = (string)$value;
		
		$r = setcookie($key, (string)$value);
		$r &= setcookie('__', $token = self::hash($arr));
		if(!$r) 
			throw new Exception('Cookie creation failed');
			
		$_COOKIE[$key] = (string)$value;
		$_COOKIE['__'] = $token;			
	}
	
	public static function get($key)
	{
		self::assertSecured($_COOKIE);	
		return isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
	}
	
	public static function reset()
	{
		$r = true;
		foreach($_COOKIE as $k=>$v) $r &= setcookie($k,'', time()-3600);
		if(!$r) 
			throw new Exception('Cookie destruction failed');
		$_COOKIE = array();
	}
	
	private static function assertSecured(array $arr)
	{
		unset($arr[ini_get('session.name')]);
		if(count($arr)===0) $arr['__'] = self::hash(array());
		if(!isset($arr['__']))
			throw new Exception('Cookie storage compromised.');
		
		if( self::hash($arr) !== $arr['__'])
			throw new Exception('Cookie storage compromised.'); 
	}
	
	private static function hash(array $arr)
	{
		unset($arr['__'], $arr[ini_get('session.name')]);
		return sha1(self::$_salt.serialize($arr));		
	}
}
?>