DbSession.php 6.11 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

Qiang Xue committed
10 11 12 13 14
use Yii;
use yii\db\Connection;
use yii\db\Query;
use yii\base\InvalidConfigException;

Qiang Xue committed
15
/**
Qiang Xue committed
16
 * DbSession extends [[Session]] by using database as session data storage.
Qiang Xue committed
17
 *
Qiang Xue committed
18
 * By default, DbSession stores session data in a DB table named 'tbl_session'. This table
19
 * must be pre-created. The table name can be changed by setting [[sessionTable]].
20
 *
21
 * The following example shows how you can configure the application to use DbSession:
22
 *
Qiang Xue committed
23
 * ~~~
24 25 26 27
 * 'session' => array(
 *     'class' => 'yii\web\DbSession',
 *     // 'db' => 'mydb',
 *     // 'sessionTable' => 'my_session',
Qiang Xue committed
28
 * )
Qiang Xue committed
29
 * ~~~
Qiang Xue committed
30
 *
31
 * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only.
32
 *
Qiang Xue committed
33
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
34
 * @since 2.0
Qiang Xue committed
35 36 37 38
 */
class DbSession extends Session
{
	/**
39 40 41
	 * @var Connection|string the DB connection object or the application component ID of the DB connection.
	 * After the DbSession object is created, if you want to change this property, you should only assign it
	 * with a DB connection object.
Qiang Xue committed
42
	 */
43
	public $db = 'db';
Qiang Xue committed
44
	/**
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	 * @var string the name of the DB table that stores the session data.
	 * The table should be pre-created as follows:
	 *
	 * ~~~
	 * CREATE TABLE tbl_session
	 * (
	 *     id CHAR(40) NOT NULL PRIMARY KEY,
	 *     expire INTEGER,
	 *     data BLOB
	 * )
	 * ~~~
	 *
	 * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
	 * that can be used for some popular DBMS:
	 *
	 * - MySQL: LONGBLOB
	 * - PostgreSQL: BYTEA
	 * - MSSQL: BLOB
	 *
	 * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
	 * column in the session table to improve the performance.
Qiang Xue committed
66
	 */
67 68
	public $sessionTable = 'tbl_session';

Qiang Xue committed
69
	/**
70 71 72
	 * Initializes the DbSession component.
	 * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
	 * @throws InvalidConfigException if [[db]] is invalid.
Qiang Xue committed
73
	 */
74 75 76 77 78 79 80
	public function init()
	{
		if (is_string($this->db)) {
			$this->db = Yii::$app->getComponent($this->db);
		}
		if (!$this->db instanceof Connection) {
			throw new InvalidConfigException("DbSession::db must be either a DB connection instance or the application component ID of a DB connection.");
81 82
		}
		parent::init();
83
	}
Qiang Xue committed
84 85 86 87 88 89 90 91 92 93 94 95

	/**
	 * Returns a value indicating whether to use custom session storage.
	 * This method overrides the parent implementation and always returns true.
	 * @return boolean whether to use custom storage.
	 */
	public function getUseCustomStorage()
	{
		return true;
	}

	/**
Qiang Xue committed
96 97
	 * Updates the current session ID with a newly generated one .
	 * Please refer to [[http://php.net/session_regenerate_id]] for more details.
Qiang Xue committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111
	 * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
	 */
	public function regenerateID($deleteOldSession = false)
	{
		$oldID = session_id();

		// if no session is started, there is nothing to regenerate
		if (empty($oldID)) {
			return;
		}

		parent::regenerateID(false);
		$newID = session_id();

Qiang Xue committed
112
		$query = new Query;
113
		$row = $query->from($this->sessionTable)
Qiang Xue committed
114
			->where(array('id' => $oldID))
115
			->createCommand($this->db)
116
			->queryOne();
Qiang Xue committed
117 118
		if ($row !== false) {
			if ($deleteOldSession) {
119 120 121
				$this->db->createCommand()
					->update($this->sessionTable, array('id' => $newID), array('id' => $oldID))
					->execute();
Qiang Xue committed
122 123
			} else {
				$row['id'] = $newID;
124 125 126
				$this->db->createCommand()
					->insert($this->sessionTable, $row)
					->execute();
Qiang Xue committed
127 128 129
			}
		} else {
			// shouldn't reach here normally
130 131 132 133 134
			$this->db->createCommand()
				->insert($this->sessionTable, array(
					'id' => $newID,
					'expire' => time() + $this->getTimeout(),
				))->execute();
Qiang Xue committed
135 136 137 138 139 140 141 142 143 144 145
		}
	}

	/**
	 * Session read handler.
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @return string the session data
	 */
	public function readSession($id)
	{
Qiang Xue committed
146 147
		$query = new Query;
		$data = $query->select(array('data'))
148
			->from($this->sessionTable)
149
			->where('[[expire]]>:expire AND [[id]]=:id', array(':expire' => time(), ':id' => $id))
150
			->createCommand($this->db)
Qiang Xue committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
			->queryScalar();
		return $data === false ? '' : $data;
	}

	/**
	 * Session write handler.
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @param string $data session data
	 * @return boolean whether session write is successful
	 */
	public function writeSession($id, $data)
	{
		// exception must be caught in session write handler
		// http://us.php.net/manual/en/function.session-set-save-handler.php
		try {
			$expire = time() + $this->getTimeout();
Qiang Xue committed
168 169
			$query = new Query;
			$exists = $query->select(array('id'))
170
				->from($this->sessionTable)
Qiang Xue committed
171
				->where(array('id' => $id))
172
				->createCommand($this->db)
Qiang Xue committed
173 174
				->queryScalar();
			if ($exists === false) {
175 176 177 178 179 180
				$this->db->createCommand()
					->insert($this->sessionTable, array(
						'id' => $id,
						'data' => $data,
						'expire' => $expire,
					))->execute();
Qiang Xue committed
181
			} else {
182 183 184
				$this->db->createCommand()
					->update($this->sessionTable, array('data' => $data, 'expire' => $expire), array('id' => $id))
					->execute();
Qiang Xue committed
185
			}
Qiang Xue committed
186
		} catch (\Exception $e) {
Qiang Xue committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
			if (YII_DEBUG) {
				echo $e->getMessage();
			}
			// it is too late to log an error message here
			return false;
		}
		return true;
	}

	/**
	 * Session destroy handler.
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @return boolean whether session is destroyed successfully
	 */
	public function destroySession($id)
	{
204 205
		$this->db->createCommand()
			->delete($this->sessionTable, array('id' => $id))
Qiang Xue committed
206
			->execute();
Qiang Xue committed
207 208 209 210 211 212 213 214 215 216 217
		return true;
	}

	/**
	 * Session GC (garbage collection) handler.
	 * Do not call this method directly.
	 * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
	 * @return boolean whether session is GCed successfully
	 */
	public function gcSession($maxLifetime)
	{
218
		$this->db->createCommand()
219
			->delete($this->sessionTable, '[[expire]]<:expire', array(':expire' => time()))
Qiang Xue committed
220
			->execute();
Qiang Xue committed
221 222 223
		return true;
	}
}