1: <?php
2:
3: namespace Session;
4:
5: class Session {
6:
7: private $id;
8: private $data;
9: private $timeout;
10: private $lastAccess;
11: private $created;
12: private $lastAccessed;
13:
14: function __construct($id, $timeout = -1)
15: {
16: $this->id = $id;
17: $this->data = array ();
18: $this->timeout = $timeout;
19: $this->lastAccess = time();
20: $this->created = time ();
21: }
22:
23: function getNames()
24: {
25: if (!$this->isValid())
26: {
27: throw new SessionException('Session timeout');
28: }
29: $ret = array ();
30: foreach ($this->data as $name => $val)
31: {
32: $ret [] = $name;
33: }
34: return $ret;
35: }
36:
37: function getCreationTime()
38: {
39: if (!$this->isValid())
40: {
41: throw new SessionException('Session timeout');
42: }
43: return $this->created;
44: }
45:
46: function getLastAccessedTime()
47: {
48:
49: return $this->lastAccessed;
50: }
51:
52: function isValid ()
53: {
54: if ($this->timeout < 0) return true;
55: $now = time ();
56: $this->lastAccessed = $now;
57: if (($now - $this->lastAccess) > $this->timeout)
58: {
59: return false;
60: } else {
61: return true;
62: }
63: }
64:
65: function updateLastAccess()
66: {
67: if (!$this->isValid())
68: {
69: throw new SessionException('Session timeout');
70: }
71: $this->lastAccess = time();
72: }
73:
74: function getTimeout ()
75: {
76: if (!$this->isValid())
77: {
78: throw new SessionException('Session timeout');
79: }
80: $this->updateLastAccess();
81: return $this->timeout;
82: }
83:
84: function setTimeout ($timeout)
85: {
86: if (!$this->isValid())
87: {
88: throw new SessionException('Session timeout');
89: }
90: $this->updateLastAccess();
91: $this->timeout = $timeout;
92: }
93:
94: function get ($key, $default = null)
95: {
96: if (!$this->isValid())
97: {
98: throw new SessionException('Session timeout');
99: }
100: $this->updateLastAccess();
101: if (isset ($this->data[$key]))
102: {
103: return $this->data[$key];
104: } else {
105: return $default;
106: }
107: }
108:
109: function set ($key, $value)
110: {
111: if (!$this->isValid())
112: {
113: throw new SessionException('Session timeout');
114: }
115: $this->updateLastAccess();
116: $this->data[$key] = $value;
117: }
118: }
119:
120: