DbSession.php 8.6 KB

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