DbSession.php 6.52 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 19
 * DbSession uses a DB application component to perform DB operations. The ID of the DB application
 * component is specified via [[connectionID]] which defaults to 'db'.
Qiang Xue committed
20
 *
Qiang Xue committed
21 22 23
 * By default, DbSession stores session data in a DB table named 'tbl_session'. This table
 * must be pre-created. The table name can be changed by setting [[sessionTableName]].
 * The table should have the following structure:
Qiang Xue committed
24
 *
Qiang Xue committed
25 26
 * ~~~
 * CREATE TABLE tbl_session
Qiang Xue committed
27 28 29 30 31
 * (
 *     id CHAR(32) PRIMARY KEY,
 *     expire INTEGER,
 *     data BLOB
 * )
Qiang Xue committed
32
 * ~~~
Qiang Xue committed
33
 *
Qiang Xue committed
34 35
 * where 'BLOB' refers to the BLOB-type of your preferred database. Below are the BLOB type
 * that can be used for some popular databases:
Qiang Xue committed
36
 *
Qiang Xue committed
37 38 39
 * - MySQL: LONGBLOB
 * - PostgreSQL: BYTEA
 * - MSSQL: BLOB
Qiang Xue committed
40
 *
Qiang Xue committed
41 42
 * 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
43 44
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
45
 * @since 2.0
Qiang Xue committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
 */
class DbSession extends Session
{
	/**
	 * @var string the ID of a {@link CDbConnection} application component. If not set, a SQLite database
	 * will be automatically created and used. The SQLite database file is
	 * is <code>protected/runtime/session-YiiVersion.db</code>.
	 */
	public $connectionID;
	/**
	 * @var string the name of the DB table to store session content.
	 * Note, if {@link autoCreateSessionTable} is false and you want to create the DB table manually by yourself,
	 * you need to make sure the DB table is of the following structure:
	 * <pre>
	 * (id CHAR(32) PRIMARY KEY, expire INTEGER, data BLOB)
	 * </pre>
	 * @see autoCreateSessionTable
	 */
Qiang Xue committed
64
	public $sessionTableName = 'tbl_session';
Qiang Xue committed
65
	/**
Qiang Xue committed
66
	 * @var Connection the DB connection instance
Qiang Xue committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
	 */
	private $_db;


	/**
	 * 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
82 83
	 * 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
84 85 86 87 88 89 90 91 92 93 94 95 96
	 * @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
97
		$db = $this->getDb();
Qiang Xue committed
98

Qiang Xue committed
99 100 101 102
		$query = new Query;
		$row = $query->from($this->sessionTableName)
			->where(array('id' => $oldID))
			->createCommand($db)
Qiang Xue committed
103 104 105 106 107
			->queryRow();
		if ($row !== false) {
			if ($deleteOldSession) {
				$db->createCommand()->update($this->sessionTableName, array(
					'id' => $newID
Qiang Xue committed
108
				), array('id' => $oldID))->execute();
Qiang Xue committed
109 110
			} else {
				$row['id'] = $newID;
Qiang Xue committed
111
				$db->createCommand()->insert($this->sessionTableName, $row)->execute();
Qiang Xue committed
112 113 114 115 116 117
			}
		} else {
			// shouldn't reach here normally
			$db->createCommand()->insert($this->sessionTableName, array(
				'id' => $newID,
				'expire' => time() + $this->getTimeout(),
Qiang Xue committed
118
			))->execute();
Qiang Xue committed
119 120
		}
	}
Qiang Xue committed
121
	
Qiang Xue committed
122
	/**
Qiang Xue committed
123 124 125
	 * Returns the DB connection instance used for storing session data.
	 * @return Connection the DB connection instance
	 * @throws InvalidConfigException if [[connectionID]] does not point to a valid application component.
Qiang Xue committed
126
	 */
Qiang Xue committed
127
	public function getDb()
Qiang Xue committed
128
	{
Qiang Xue committed
129 130 131 132
		if ($this->_db === null) {
			$db = Yii::$app->getComponent($this->connectionID);
			if ($db instanceof Connection) {
				$this->_db = $db;
Qiang Xue committed
133
			} else {
Qiang Xue committed
134
				throw new InvalidConfigException("DbSession::connectionID must refer to the ID of a DB application component.");
Qiang Xue committed
135 136
			}
		}
Qiang Xue committed
137
		return $this->_db;
Qiang Xue committed
138 139 140
	}

	/**
Qiang Xue committed
141 142
	 * Sets the DB connection used by the session component.
	 * @param Connection $value the DB connection instance
Qiang Xue committed
143
	 */
Qiang Xue committed
144
	public function setDb($value)
Qiang Xue committed
145
	{
Qiang Xue committed
146
		$this->_db = $value;
Qiang Xue committed
147 148 149 150 151 152 153 154 155 156
	}

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