1 <?php defined('SYSPATH') OR die('No direct access allowed.');
3 * Session database driver.
5 * $Id: Database.php 3769 2008-12-15 00:48:56Z zombor $
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 class Session_Database_Driver implements Session_Driver {
17 session_id VARCHAR(127) NOT NULL,
18 last_activity INT(10) UNSIGNED NOT NULL,
20 PRIMARY KEY (session_id)
25 protected $db = 'default';
26 protected $table = 'sessions';
32 protected $session_id;
33 protected $written = FALSE;
35 public function __construct()
38 $config = Kohana::config('session');
40 if ( ! empty($config['encryption']))
43 $this->encrypt = Encrypt::instance();
46 if (is_array($config['storage']))
48 if ( ! empty($config['storage']['group']))
51 $this->db = $config['storage']['group'];
54 if ( ! empty($config['storage']['table']))
57 $this->table = $config['storage']['table'];
62 $this->db = Database::instance($this->db);
64 Kohana::log('debug', 'Session Database Driver Initialized');
67 public function open($path, $name)
72 public function close()
77 public function read($id)
80 $query = $this->db->from($this->table)->where('session_id', $id)->limit(1)->get()->result(TRUE);
82 if ($query->count() === 0)
85 $this->session_id = NULL;
90 // Set the current session id
91 $this->session_id = $id;
94 $data = $query->current()->data;
96 return ($this->encrypt === NULL) ? base64_decode($data) : $this->encrypt->decode($data);
99 public function write($id, $data)
104 'last_activity' => time(),
105 'data' => ($this->encrypt === NULL) ? base64_encode($data) : $this->encrypt->encode($data)
108 if ($this->session_id === NULL)
110 // Insert a new session
111 $query = $this->db->insert($this->table, $data);
113 elseif ($id === $this->session_id)
115 // Do not update the session_id
116 unset($data['session_id']);
118 // Update the existing session
119 $query = $this->db->update($this->table, $data, array('session_id' => $id));
123 // Update the session and id
124 $query = $this->db->update($this->table, $data, array('session_id' => $this->session_id));
126 // Set the new session id
127 $this->session_id = $id;
130 return (bool) $query->count();
133 public function destroy($id)
135 // Delete the requested session
136 $this->db->delete($this->table, array('session_id' => $id));
138 // Session id is no longer valid
139 $this->session_id = NULL;
144 public function regenerate()
146 // Generate a new session id
147 session_regenerate_id();
149 // Return new session id
153 public function gc($maxlifetime)
155 // Delete all expired sessions
156 $query = $this->db->delete($this->table, array('last_activity <' => time() - $maxlifetime));
158 Kohana::log('debug', 'Session garbage collected: '.$query->count().' row(s) deleted.');
163 } // End Session Database Driver