DbSession.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\db\Connection;
  11. use yii\db\PdoValue;
  12. use yii\db\Query;
  13. use yii\di\Instance;
  14. /**
  15. * DbSession extends [[Session]] by using database as session data storage.
  16. *
  17. * By default, DbSession stores session data in a DB table named 'session'. This table
  18. * must be pre-created. The table name can be changed by setting [[sessionTable]].
  19. *
  20. * The following example shows how you can configure the application to use DbSession:
  21. * Add the following to your application config under `components`:
  22. *
  23. * ```php
  24. * 'session' => [
  25. * 'class' => 'yii\web\DbSession',
  26. * // 'db' => 'mydb',
  27. * // 'sessionTable' => 'my_session',
  28. * ]
  29. * ```
  30. *
  31. * DbSession extends [[MultiFieldSession]], thus it allows saving extra fields into the [[sessionTable]].
  32. * Refer to [[MultiFieldSession]] for more details.
  33. *
  34. * @author Qiang Xue <qiang.xue@gmail.com>
  35. * @since 2.0
  36. */
  37. class DbSession extends MultiFieldSession
  38. {
  39. /**
  40. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  41. * After the DbSession object is created, if you want to change this property, you should only assign it
  42. * with a DB connection object.
  43. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  44. */
  45. public $db = 'db';
  46. /**
  47. * @var string the name of the DB table that stores the session data.
  48. * The table should be pre-created as follows:
  49. *
  50. * ```sql
  51. * CREATE TABLE session
  52. * (
  53. * id CHAR(40) NOT NULL PRIMARY KEY,
  54. * expire INTEGER,
  55. * data BLOB
  56. * )
  57. * ```
  58. *
  59. * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
  60. * that can be used for some popular DBMS:
  61. *
  62. * - MySQL: LONGBLOB
  63. * - PostgreSQL: BYTEA
  64. * - MSSQL: BLOB
  65. *
  66. * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
  67. * column in the session table to improve the performance.
  68. *
  69. * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
  70. * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
  71. * length 64 instead of 40.
  72. */
  73. public $sessionTable = '{{%session}}';
  74. /**
  75. * @var array Session fields to be written into session table columns
  76. * @since 2.0.17
  77. */
  78. protected $fields = [];
  79. /**
  80. * Initializes the DbSession component.
  81. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  82. * @throws InvalidConfigException if [[db]] is invalid.
  83. */
  84. public function init()
  85. {
  86. parent::init();
  87. $this->db = Instance::ensure($this->db, Connection::className());
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function regenerateID($deleteOldSession = false)
  93. {
  94. $oldID = session_id();
  95. // if no session is started, there is nothing to regenerate
  96. if (empty($oldID)) {
  97. return;
  98. }
  99. parent::regenerateID(false);
  100. $newID = session_id();
  101. // if session id regeneration failed, no need to create/update it.
  102. if (empty($newID)) {
  103. Yii::warning('Failed to generate new session ID', __METHOD__);
  104. return;
  105. }
  106. $row = $this->db->useMaster(function() use ($oldID) {
  107. return (new Query())->from($this->sessionTable)
  108. ->where(['id' => $oldID])
  109. ->createCommand($this->db)
  110. ->queryOne();
  111. });
  112. if ($row !== false) {
  113. if ($deleteOldSession) {
  114. $this->db->createCommand()
  115. ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
  116. ->execute();
  117. } else {
  118. $row['id'] = $newID;
  119. $this->db->createCommand()
  120. ->insert($this->sessionTable, $row)
  121. ->execute();
  122. }
  123. } else {
  124. // shouldn't reach here normally
  125. $this->db->createCommand()
  126. ->insert($this->sessionTable, $this->composeFields($newID, ''))
  127. ->execute();
  128. }
  129. }
  130. /**
  131. * Ends the current session and store session data.
  132. * @since 2.0.17
  133. */
  134. public function close()
  135. {
  136. if ($this->getIsActive()) {
  137. // prepare writeCallback fields before session closes
  138. $this->fields = $this->composeFields();
  139. YII_DEBUG ? session_write_close() : @session_write_close();
  140. }
  141. }
  142. /**
  143. * Session read handler.
  144. * @internal Do not call this method directly.
  145. * @param string $id session ID
  146. * @return string the session data
  147. */
  148. public function readSession($id)
  149. {
  150. $query = new Query();
  151. $query->from($this->sessionTable)
  152. ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
  153. if ($this->readCallback !== null) {
  154. $fields = $query->one($this->db);
  155. return $fields === false ? '' : $this->extractData($fields);
  156. }
  157. $data = $query->select(['data'])->scalar($this->db);
  158. return $data === false ? '' : $data;
  159. }
  160. /**
  161. * Session write handler.
  162. * @internal Do not call this method directly.
  163. * @param string $id session ID
  164. * @param string $data session data
  165. * @return bool whether session write is successful
  166. */
  167. public function writeSession($id, $data)
  168. {
  169. // exception must be caught in session write handler
  170. // https://secure.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
  171. try {
  172. // ensure backwards compatability (fixed #9438)
  173. if ($this->writeCallback && !$this->fields) {
  174. $this->fields = $this->composeFields();
  175. }
  176. // ensure data consistency
  177. if (!isset($this->fields['data'])) {
  178. $this->fields['data'] = $data;
  179. } else {
  180. $_SESSION = $this->fields['data'];
  181. }
  182. // ensure 'id' and 'expire' are never affected by [[writeCallback]]
  183. $this->fields = array_merge($this->fields, [
  184. 'id' => $id,
  185. 'expire' => time() + $this->getTimeout(),
  186. ]);
  187. $this->fields = $this->typecastFields($this->fields);
  188. $this->db->createCommand()->upsert($this->sessionTable, $this->fields)->execute();
  189. $this->fields = [];
  190. } catch (\Exception $e) {
  191. Yii::$app->errorHandler->handleException($e);
  192. return false;
  193. }
  194. return true;
  195. }
  196. /**
  197. * Session destroy handler.
  198. * @internal Do not call this method directly.
  199. * @param string $id session ID
  200. * @return bool whether session is destroyed successfully
  201. */
  202. public function destroySession($id)
  203. {
  204. $this->db->createCommand()
  205. ->delete($this->sessionTable, ['id' => $id])
  206. ->execute();
  207. return true;
  208. }
  209. /**
  210. * Session GC (garbage collection) handler.
  211. * @internal Do not call this method directly.
  212. * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  213. * @return bool whether session is GCed successfully
  214. */
  215. public function gcSession($maxLifetime)
  216. {
  217. $this->db->createCommand()
  218. ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
  219. ->execute();
  220. return true;
  221. }
  222. /**
  223. * Method typecasts $fields before passing them to PDO.
  224. * Default implementation casts field `data` to `\PDO::PARAM_LOB`.
  225. * You can override this method in case you need special type casting.
  226. *
  227. * @param array $fields Fields, that will be passed to PDO. Key - name, Value - value
  228. * @return array
  229. * @since 2.0.13
  230. */
  231. protected function typecastFields($fields)
  232. {
  233. if (isset($fields['data']) && !is_array($fields['data']) && !is_object($fields['data'])) {
  234. $fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
  235. }
  236. return $fields;
  237. }
  238. }