DbSession.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. * Initializes the DbSession component.
  77. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  78. * @throws InvalidConfigException if [[db]] is invalid.
  79. */
  80. public function init()
  81. {
  82. parent::init();
  83. $this->db = Instance::ensure($this->db, Connection::className());
  84. }
  85. /**
  86. * Updates the current session ID with a newly generated one .
  87. * Please refer to <http://php.net/session_regenerate_id> for more details.
  88. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  89. */
  90. public function regenerateID($deleteOldSession = false)
  91. {
  92. $oldID = session_id();
  93. // if no session is started, there is nothing to regenerate
  94. if (empty($oldID)) {
  95. return;
  96. }
  97. parent::regenerateID(false);
  98. $newID = session_id();
  99. // if session id regeneration failed, no need to create/update it.
  100. if (empty($newID)) {
  101. Yii::warning('Failed to generate new session ID', __METHOD__);
  102. return;
  103. }
  104. $row = $this->db->useMaster(function() use ($oldID) {
  105. return (new Query())->from($this->sessionTable)
  106. ->where(['id' => $oldID])
  107. ->createCommand($this->db)
  108. ->queryOne();
  109. });
  110. if ($row !== false) {
  111. if ($deleteOldSession) {
  112. $this->db->createCommand()
  113. ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
  114. ->execute();
  115. } else {
  116. $row['id'] = $newID;
  117. $this->db->createCommand()
  118. ->insert($this->sessionTable, $row)
  119. ->execute();
  120. }
  121. } else {
  122. // shouldn't reach here normally
  123. $this->db->createCommand()
  124. ->insert($this->sessionTable, $this->composeFields($newID, ''))
  125. ->execute();
  126. }
  127. }
  128. /**
  129. * Session read handler.
  130. * @internal Do not call this method directly.
  131. * @param string $id session ID
  132. * @return string the session data
  133. */
  134. public function readSession($id)
  135. {
  136. $query = new Query();
  137. $query->from($this->sessionTable)
  138. ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
  139. if ($this->readCallback !== null) {
  140. $fields = $query->one($this->db);
  141. return $fields === false ? '' : $this->extractData($fields);
  142. }
  143. $data = $query->select(['data'])->scalar($this->db);
  144. return $data === false ? '' : $data;
  145. }
  146. /**
  147. * Session write handler.
  148. * @internal Do not call this method directly.
  149. * @param string $id session ID
  150. * @param string $data session data
  151. * @return bool whether session write is successful
  152. */
  153. public function writeSession($id, $data)
  154. {
  155. // exception must be caught in session write handler
  156. // http://us.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
  157. try {
  158. $fields = $this->composeFields($id, $data);
  159. $fields = $this->typecastFields($fields);
  160. $this->db->createCommand()->upsert($this->sessionTable, $fields)->execute();
  161. } catch (\Exception $e) {
  162. Yii::$app->errorHandler->handleException($e);
  163. return false;
  164. }
  165. return true;
  166. }
  167. /**
  168. * Session destroy handler.
  169. * @internal Do not call this method directly.
  170. * @param string $id session ID
  171. * @return bool whether session is destroyed successfully
  172. */
  173. public function destroySession($id)
  174. {
  175. $this->db->createCommand()
  176. ->delete($this->sessionTable, ['id' => $id])
  177. ->execute();
  178. return true;
  179. }
  180. /**
  181. * Session GC (garbage collection) handler.
  182. * @internal Do not call this method directly.
  183. * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  184. * @return bool whether session is GCed successfully
  185. */
  186. public function gcSession($maxLifetime)
  187. {
  188. $this->db->createCommand()
  189. ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
  190. ->execute();
  191. return true;
  192. }
  193. /**
  194. * Method typecasts $fields before passing them to PDO.
  195. * Default implementation casts field `data` to `\PDO::PARAM_LOB`.
  196. * You can override this method in case you need special type casting.
  197. *
  198. * @param array $fields Fields, that will be passed to PDO. Key - name, Value - value
  199. * @return array
  200. * @since 2.0.13
  201. */
  202. protected function typecastFields($fields)
  203. {
  204. if (isset($fields['data']) && is_array($fields['data'] && is_object($fields['data']))) {
  205. $fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
  206. }
  207. return $fields;
  208. }
  209. }