DbSession.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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\db\Connection;
  10. use yii\db\Query;
  11. use yii\base\InvalidConfigException;
  12. use yii\di\Instance;
  13. /**
  14. * DbSession extends [[Session]] by using database as session data storage.
  15. *
  16. * By default, DbSession stores session data in a DB table named 'session'. This table
  17. * must be pre-created. The table name can be changed by setting [[sessionTable]].
  18. *
  19. * The following example shows how you can configure the application to use DbSession:
  20. * Add the following to your application config under `components`:
  21. *
  22. * ```php
  23. * 'session' => [
  24. * 'class' => 'yii\web\DbSession',
  25. * // 'db' => 'mydb',
  26. * // 'sessionTable' => 'my_session',
  27. * ]
  28. * ```
  29. *
  30. * DbSession extends [[MultiFieldSession]], thus it allows saving extra fields into the [[sessionTable]].
  31. * Refer to [[MultiFieldSession]] for more details.
  32. *
  33. * @author Qiang Xue <qiang.xue@gmail.com>
  34. * @since 2.0
  35. */
  36. class DbSession extends MultiFieldSession
  37. {
  38. /**
  39. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  40. * After the DbSession object is created, if you want to change this property, you should only assign it
  41. * with a DB connection object.
  42. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  43. */
  44. public $db = 'db';
  45. /**
  46. * @var string the name of the DB table that stores the session data.
  47. * The table should be pre-created as follows:
  48. *
  49. * ```sql
  50. * CREATE TABLE session
  51. * (
  52. * id CHAR(40) NOT NULL PRIMARY KEY,
  53. * expire INTEGER,
  54. * data BLOB
  55. * )
  56. * ```
  57. *
  58. * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
  59. * that can be used for some popular DBMS:
  60. *
  61. * - MySQL: LONGBLOB
  62. * - PostgreSQL: BYTEA
  63. * - MSSQL: BLOB
  64. *
  65. * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
  66. * column in the session table to improve the performance.
  67. *
  68. * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
  69. * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
  70. * length 64 instead of 40.
  71. */
  72. public $sessionTable = '{{%session}}';
  73. /**
  74. * Initializes the DbSession component.
  75. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  76. * @throws InvalidConfigException if [[db]] is invalid.
  77. */
  78. public function init()
  79. {
  80. parent::init();
  81. $this->db = Instance::ensure($this->db, Connection::className());
  82. }
  83. /**
  84. * Updates the current session ID with a newly generated one .
  85. * Please refer to <http://php.net/session_regenerate_id> for more details.
  86. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  87. */
  88. public function regenerateID($deleteOldSession = false)
  89. {
  90. $oldID = session_id();
  91. // if no session is started, there is nothing to regenerate
  92. if (empty($oldID)) {
  93. return;
  94. }
  95. parent::regenerateID(false);
  96. $newID = session_id();
  97. // if session id regeneration failed, no need to create/update it.
  98. if (empty($newID)) {
  99. Yii::warning('Failed to generate new session ID', __METHOD__);
  100. return;
  101. }
  102. $query = new Query();
  103. $row = $query->from($this->sessionTable)
  104. ->where(['id' => $oldID])
  105. ->createCommand($this->db)
  106. ->queryOne();
  107. if ($row !== false) {
  108. if ($deleteOldSession) {
  109. $this->db->createCommand()
  110. ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
  111. ->execute();
  112. } else {
  113. $row['id'] = $newID;
  114. $this->db->createCommand()
  115. ->insert($this->sessionTable, $row)
  116. ->execute();
  117. }
  118. } else {
  119. // shouldn't reach here normally
  120. $this->db->createCommand()
  121. ->insert($this->sessionTable, $this->composeFields($newID, ''))
  122. ->execute();
  123. }
  124. }
  125. /**
  126. * Session read handler.
  127. * Do not call this method directly.
  128. * @param string $id session ID
  129. * @return string the session data
  130. */
  131. public function readSession($id)
  132. {
  133. $query = new Query();
  134. $query->from($this->sessionTable)
  135. ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
  136. if ($this->readCallback !== null) {
  137. $fields = $query->one($this->db);
  138. return $fields === false ? '' : $this->extractData($fields);
  139. }
  140. $data = $query->select(['data'])->scalar($this->db);
  141. return $data === false ? '' : $data;
  142. }
  143. /**
  144. * Session write handler.
  145. * Do not call this method directly.
  146. * @param string $id session ID
  147. * @param string $data session data
  148. * @return bool whether session write is successful
  149. */
  150. public function writeSession($id, $data)
  151. {
  152. // exception must be caught in session write handler
  153. // http://us.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
  154. try {
  155. $query = new Query;
  156. $exists = $query->select(['id'])
  157. ->from($this->sessionTable)
  158. ->where(['id' => $id])
  159. ->createCommand($this->db)
  160. ->queryScalar();
  161. $fields = $this->composeFields($id, $data);
  162. if ($exists === false) {
  163. $this->db->createCommand()
  164. ->insert($this->sessionTable, $fields)
  165. ->execute();
  166. } else {
  167. unset($fields['id']);
  168. $this->db->createCommand()
  169. ->update($this->sessionTable, $fields, ['id' => $id])
  170. ->execute();
  171. }
  172. } catch (\Exception $e) {
  173. $exception = ErrorHandler::convertExceptionToString($e);
  174. // its too late to use Yii logging here
  175. error_log($exception);
  176. if (YII_DEBUG) {
  177. echo $exception;
  178. }
  179. return false;
  180. }
  181. return true;
  182. }
  183. /**
  184. * Session destroy handler.
  185. * Do not call this method directly.
  186. * @param string $id session ID
  187. * @return bool whether session is destroyed successfully
  188. */
  189. public function destroySession($id)
  190. {
  191. $this->db->createCommand()
  192. ->delete($this->sessionTable, ['id' => $id])
  193. ->execute();
  194. return true;
  195. }
  196. /**
  197. * Session GC (garbage collection) handler.
  198. * Do not call this method directly.
  199. * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  200. * @return bool whether session is GCed successfully
  201. */
  202. public function gcSession($maxLifetime)
  203. {
  204. $this->db->createCommand()
  205. ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
  206. ->execute();
  207. return true;
  208. }
  209. }