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
 * Add the following to your application config under `components`:
23
 *
Qiang Xue committed
24
 * ~~~
Alexander Makarov committed
25
 * 'session' => [
26 27 28
 *     'class' => 'yii\web\DbSession',
 *     // 'db' => 'mydb',
 *     // 'sessionTable' => 'my_session',
Alexander Makarov committed
29
 * ]
Qiang Xue committed
30
 * ~~~
Qiang Xue committed
31
 *
32
 * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only.
33
 *
Qiang Xue committed
34
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
35
 * @since 2.0
Qiang Xue committed
36 37 38 39
 */
class DbSession extends Session
{
	/**
40 41 42
	 * @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
43
	 */
44
	public $db = 'db';
Qiang Xue committed
45
	/**
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	 * @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
67
	 */
68
	public $sessionTable = '{{%session}}';
69

Qiang Xue committed
70
	/**
71 72 73
	 * 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
74
	 */
75 76 77 78 79 80 81
	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.");
82 83
		}
		parent::init();
84
	}
Qiang Xue committed
85 86 87 88 89 90 91 92 93 94 95 96

	/**
	 * 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
97
	 * Updates the current session ID with a newly generated one .
Carsten Brandt committed
98
	 * Please refer to <http://php.net/session_regenerate_id> for more details.
Qiang Xue committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112
	 * @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
113
		$query = new Query;
114
		$row = $query->from($this->sessionTable)
Alexander Makarov committed
115
			->where(['id' => $oldID])
116
			->createCommand($this->db)
117
			->queryOne();
Qiang Xue committed
118 119
		if ($row !== false) {
			if ($deleteOldSession) {
120
				$this->db->createCommand()
Alexander Makarov committed
121
					->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
122
					->execute();
Qiang Xue committed
123 124
			} else {
				$row['id'] = $newID;
125 126 127
				$this->db->createCommand()
					->insert($this->sessionTable, $row)
					->execute();
Qiang Xue committed
128 129 130
			}
		} else {
			// shouldn't reach here normally
131
			$this->db->createCommand()
Alexander Makarov committed
132
				->insert($this->sessionTable, [
133 134
					'id' => $newID,
					'expire' => time() + $this->getTimeout(),
Alexander Makarov committed
135
				])->execute();
Qiang Xue committed
136 137 138 139 140 141 142 143 144 145 146
		}
	}

	/**
	 * 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
147
		$query = new Query;
Alexander Makarov committed
148
		$data = $query->select(['data'])
149
			->from($this->sessionTable)
Alexander Makarov committed
150
			->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id])
151
			->createCommand($this->db)
Qiang Xue committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
			->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
169
			$query = new Query;
Alexander Makarov committed
170
			$exists = $query->select(['id'])
171
				->from($this->sessionTable)
Alexander Makarov committed
172
				->where(['id' => $id])
173
				->createCommand($this->db)
Qiang Xue committed
174 175
				->queryScalar();
			if ($exists === false) {
176
				$this->db->createCommand()
Alexander Makarov committed
177
					->insert($this->sessionTable, [
178 179 180
						'id' => $id,
						'data' => $data,
						'expire' => $expire,
Alexander Makarov committed
181
					])->execute();
Qiang Xue committed
182
			} else {
183
				$this->db->createCommand()
Alexander Makarov committed
184
					->update($this->sessionTable, ['data' => $data, 'expire' => $expire], ['id' => $id])
185
					->execute();
Qiang Xue committed
186
			}
Qiang Xue committed
187
		} catch (\Exception $e) {
Qiang Xue committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
			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)
	{
205
		$this->db->createCommand()
Alexander Makarov committed
206
			->delete($this->sessionTable, ['id' => $id])
Qiang Xue committed
207
			->execute();
Qiang Xue committed
208 209 210 211 212 213 214 215 216 217 218
		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)
	{
219
		$this->db->createCommand()
Alexander Makarov committed
220
			->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
Qiang Xue committed
221
			->execute();
Qiang Xue committed
222 223 224
		return true;
	}
}