Session.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidArgumentException;
  11. use yii\base\InvalidConfigException;
  12. /**
  13. * Session provides session data management and the related configurations.
  14. *
  15. * Session is a Web application component that can be accessed via `Yii::$app->session`.
  16. *
  17. * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
  18. * To destroy the session, call [[destroy()]].
  19. *
  20. * Session can be used like an array to set and get session data. For example,
  21. *
  22. * ```php
  23. * $session = new Session;
  24. * $session->open();
  25. * $value1 = $session['name1']; // get session variable 'name1'
  26. * $value2 = $session['name2']; // get session variable 'name2'
  27. * foreach ($session as $name => $value) // traverse all session variables
  28. * $session['name3'] = $value3; // set session variable 'name3'
  29. * ```
  30. *
  31. * Session can be extended to support customized session storage.
  32. * To do so, override [[useCustomStorage]] so that it returns true, and
  33. * override these methods with the actual logic about using custom storage:
  34. * [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
  35. * [[destroySession()]] and [[gcSession()]].
  36. *
  37. * Session also supports a special type of session data, called *flash messages*.
  38. * A flash message is available only in the current request and the next request.
  39. * After that, it will be deleted automatically. Flash messages are particularly
  40. * useful for displaying confirmation messages. To use flash messages, simply
  41. * call methods such as [[setFlash()]], [[getFlash()]].
  42. *
  43. * For more details and usage information on Session, see the [guide article on sessions](guide:runtime-sessions-cookies).
  44. *
  45. * @property-read array $allFlashes Flash messages (key => message or key => [message1, message2]).
  46. * @property-read string $cacheLimiter Current cache limiter.
  47. * @property-read array $cookieParams The session cookie parameters.
  48. * @property-read int $count The number of session variables.
  49. * @property-write string $flash The key identifying the flash message. Note that flash messages and normal
  50. * session variables share the same name space. If you have a normal session variable using the same name, its
  51. * value will be overwritten by this method.
  52. * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
  53. * started on every session initialization.
  54. * @property bool $hasSessionId Whether the current request has sent the session ID.
  55. * @property string $id The current session ID.
  56. * @property-read bool $isActive Whether the session has started.
  57. * @property-read SessionIterator $iterator An iterator for traversing the session variables.
  58. * @property string $name The current session name.
  59. * @property string $savePath The current session save path, defaults to '/tmp'.
  60. * @property int $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. The
  61. * default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
  62. * @property bool|null $useCookies The value indicating whether cookies should be used to store session IDs.
  63. * @property-read bool $useCustomStorage Whether to use custom storage.
  64. * @property bool $useStrictMode Whether strict mode is enabled or not.
  65. * @property bool $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to
  66. * false.
  67. *
  68. * @author Qiang Xue <qiang.xue@gmail.com>
  69. * @since 2.0
  70. */
  71. class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
  72. {
  73. /**
  74. * @var string|null Holds the original session module (before a custom handler is registered) so that it can be
  75. * restored when a Session component without custom handler is used after one that has.
  76. */
  77. protected static $_originalSessionModule = null;
  78. /**
  79. * Polyfill for ini directive session.use-strict-mode for PHP < 5.5.2.
  80. */
  81. private static $_useStrictModePolyfill = false;
  82. /**
  83. * @var string the name of the session variable that stores the flash message data.
  84. */
  85. public $flashParam = '__flash';
  86. /**
  87. * @var \SessionHandlerInterface|array an object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.
  88. */
  89. public $handler;
  90. /**
  91. * @var string|null Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated
  92. */
  93. protected $_forceRegenerateId = null;
  94. /**
  95. * @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
  96. * Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
  97. * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
  98. */
  99. private $_cookieParams = ['httponly' => true];
  100. /**
  101. * @var array|null is used for saving session between recreations due to session parameters update.
  102. */
  103. private $_frozenSessionData;
  104. /**
  105. * Initializes the application component.
  106. * This method is required by IApplicationComponent and is invoked by application.
  107. */
  108. public function init()
  109. {
  110. parent::init();
  111. register_shutdown_function([$this, 'close']);
  112. if ($this->getIsActive()) {
  113. Yii::warning('Session is already started', __METHOD__);
  114. $this->updateFlashCounters();
  115. }
  116. }
  117. /**
  118. * Returns a value indicating whether to use custom session storage.
  119. * This method should be overridden to return true by child classes that implement custom session storage.
  120. * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
  121. * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
  122. * @return bool whether to use custom storage.
  123. */
  124. public function getUseCustomStorage()
  125. {
  126. return false;
  127. }
  128. /**
  129. * Starts the session.
  130. */
  131. public function open()
  132. {
  133. if ($this->getIsActive()) {
  134. return;
  135. }
  136. $this->registerSessionHandler();
  137. if ($this->getUseCookies() !== false) {
  138. $this->setCookieParamsInternal();
  139. }
  140. YII_DEBUG ? session_start() : @session_start();
  141. if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
  142. $this->regenerateID();
  143. $this->_forceRegenerateId = null;
  144. }
  145. if ($this->getIsActive()) {
  146. Yii::info('Session started', __METHOD__);
  147. $this->updateFlashCounters();
  148. } else {
  149. $error = error_get_last();
  150. $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
  151. Yii::error($message, __METHOD__);
  152. }
  153. }
  154. /**
  155. * Registers session handler.
  156. * @throws \yii\base\InvalidConfigException
  157. */
  158. protected function registerSessionHandler()
  159. {
  160. $sessionModuleName = session_module_name();
  161. if (static::$_originalSessionModule === null) {
  162. static::$_originalSessionModule = $sessionModuleName;
  163. }
  164. if ($this->handler === null && $this->getUseCustomStorage()) {
  165. $this->handler = Yii::createObject(
  166. [
  167. '__class' => SessionHandler::class,
  168. '__construct()' => [$this],
  169. ]
  170. );
  171. }
  172. if ($this->handler !== null) {
  173. if (is_array($this->handler)) {
  174. $this->handler = Yii::createObject($this->handler);
  175. }
  176. if (!$this->handler instanceof \SessionHandlerInterface) {
  177. throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
  178. }
  179. YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
  180. } elseif (
  181. $sessionModuleName !== static::$_originalSessionModule
  182. && static::$_originalSessionModule !== null
  183. && static::$_originalSessionModule !== 'user'
  184. ) {
  185. session_module_name(static::$_originalSessionModule);
  186. }
  187. }
  188. /**
  189. * Ends the current session and store session data.
  190. */
  191. public function close()
  192. {
  193. if ($this->getIsActive()) {
  194. YII_DEBUG ? session_write_close() : @session_write_close();
  195. }
  196. $this->_forceRegenerateId = null;
  197. }
  198. /**
  199. * Frees all session variables and destroys all data registered to a session.
  200. *
  201. * This method has no effect when session is not [[getIsActive()|active]].
  202. * Make sure to call [[open()]] before calling it.
  203. * @see open()
  204. * @see isActive
  205. */
  206. public function destroy()
  207. {
  208. if ($this->getIsActive()) {
  209. $sessionId = session_id();
  210. $this->close();
  211. $this->setId($sessionId);
  212. $this->open();
  213. session_unset();
  214. session_destroy();
  215. $this->setId($sessionId);
  216. }
  217. }
  218. /**
  219. * @return bool whether the session has started
  220. */
  221. public function getIsActive()
  222. {
  223. return session_status() === PHP_SESSION_ACTIVE;
  224. }
  225. private $_hasSessionId;
  226. /**
  227. * Returns a value indicating whether the current request has sent the session ID.
  228. * The default implementation will check cookie and $_GET using the session name.
  229. * If you send session ID via other ways, you may need to override this method
  230. * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
  231. * @return bool whether the current request has sent the session ID.
  232. */
  233. public function getHasSessionId()
  234. {
  235. if ($this->_hasSessionId === null) {
  236. $name = $this->getName();
  237. $request = Yii::$app->getRequest();
  238. if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
  239. $this->_hasSessionId = true;
  240. } elseif (PHP_VERSION_ID < 80400 && !ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
  241. $this->_hasSessionId = $request->get($name) != '';
  242. } else {
  243. $this->_hasSessionId = false;
  244. }
  245. }
  246. return $this->_hasSessionId;
  247. }
  248. /**
  249. * Sets the value indicating whether the current request has sent the session ID.
  250. * This method is provided so that you can override the default way of determining
  251. * whether the session ID is sent.
  252. * @param bool $value whether the current request has sent the session ID.
  253. */
  254. public function setHasSessionId($value)
  255. {
  256. $this->_hasSessionId = $value;
  257. }
  258. /**
  259. * Gets the session ID.
  260. * This is a wrapper for [PHP session_id()](https://www.php.net/manual/en/function.session-id.php).
  261. * @return string the current session ID
  262. */
  263. public function getId()
  264. {
  265. return session_id();
  266. }
  267. /**
  268. * Sets the session ID.
  269. * This is a wrapper for [PHP session_id()](https://www.php.net/manual/en/function.session-id.php).
  270. * @param string $value the session ID for the current session
  271. */
  272. public function setId($value)
  273. {
  274. session_id($value);
  275. }
  276. /**
  277. * Updates the current session ID with a newly generated one.
  278. *
  279. * Please refer to <https://www.php.net/session_regenerate_id> for more details.
  280. *
  281. * This method has no effect when session is not [[getIsActive()|active]].
  282. * Make sure to call [[open()]] before calling it.
  283. *
  284. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  285. * @see open()
  286. * @see isActive
  287. */
  288. public function regenerateID($deleteOldSession = false)
  289. {
  290. if ($this->getIsActive()) {
  291. // add @ to inhibit possible warning due to race condition
  292. // https://github.com/yiisoft/yii2/pull/1812
  293. if (YII_DEBUG && !headers_sent()) {
  294. session_regenerate_id($deleteOldSession);
  295. } else {
  296. @session_regenerate_id($deleteOldSession);
  297. }
  298. }
  299. }
  300. /**
  301. * Gets the name of the current session.
  302. * This is a wrapper for [PHP session_name()](https://www.php.net/manual/en/function.session-name.php).
  303. * @return string the current session name
  304. */
  305. public function getName()
  306. {
  307. return session_name();
  308. }
  309. /**
  310. * Sets the name for the current session.
  311. * This is a wrapper for [PHP session_name()](https://www.php.net/manual/en/function.session-name.php).
  312. * @param string $value the session name for the current session, must be an alphanumeric string.
  313. * It defaults to "PHPSESSID".
  314. */
  315. public function setName($value)
  316. {
  317. $this->freeze();
  318. session_name($value);
  319. $this->unfreeze();
  320. }
  321. /**
  322. * Gets the current session save path.
  323. * This is a wrapper for [PHP session_save_path()](https://www.php.net/manual/en/function.session-save-path.php).
  324. * @return string the current session save path, defaults to '/tmp'.
  325. */
  326. public function getSavePath()
  327. {
  328. return session_save_path();
  329. }
  330. /**
  331. * Sets the current session save path.
  332. * This is a wrapper for [PHP session_save_path()](https://www.php.net/manual/en/function.session-save-path.php).
  333. * @param string $value the current session save path. This can be either a directory name or a [path alias](guide:concept-aliases).
  334. * @throws InvalidArgumentException if the path is not a valid directory
  335. */
  336. public function setSavePath($value)
  337. {
  338. $path = Yii::getAlias($value);
  339. if (is_dir($path)) {
  340. session_save_path($path);
  341. } else {
  342. throw new InvalidArgumentException("Session save path is not a valid directory: $value");
  343. }
  344. }
  345. /**
  346. * @return array the session cookie parameters.
  347. * @see https://www.php.net/manual/en/function.session-get-cookie-params.php
  348. */
  349. public function getCookieParams()
  350. {
  351. return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
  352. }
  353. /**
  354. * Sets the session cookie parameters.
  355. * The cookie parameters passed to this method will be merged with the result
  356. * of `session_get_cookie_params()`.
  357. * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httponly`.
  358. * Starting with Yii 2.0.21 `sameSite` is also supported. It requires PHP version 7.3.0 or higher.
  359. * For security, an exception will be thrown if `sameSite` is set while using an unsupported version of PHP.
  360. * To use this feature across different PHP versions check the version first. E.g.
  361. * ```php
  362. * [
  363. * 'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,
  364. * ]
  365. * ```
  366. * See https://owasp.org/www-community/SameSite for more information about `sameSite`.
  367. *
  368. * @throws InvalidArgumentException if the parameters are incomplete.
  369. * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
  370. */
  371. public function setCookieParams(array $value)
  372. {
  373. $this->_cookieParams = $value;
  374. }
  375. /**
  376. * Sets the session cookie parameters.
  377. * This method is called by [[open()]] when it is about to open the session.
  378. * @throws InvalidArgumentException if the parameters are incomplete.
  379. * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
  380. */
  381. private function setCookieParamsInternal()
  382. {
  383. $data = $this->getCookieParams();
  384. if (isset($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly'])) {
  385. if (PHP_VERSION_ID >= 70300) {
  386. session_set_cookie_params($data);
  387. } else {
  388. if (!empty($data['samesite'])) {
  389. $data['path'] .= '; samesite=' . $data['samesite'];
  390. }
  391. session_set_cookie_params($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly']);
  392. }
  393. } else {
  394. throw new InvalidArgumentException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.');
  395. }
  396. }
  397. /**
  398. * Returns the value indicating whether cookies should be used to store session IDs.
  399. * @return bool|null the value indicating whether cookies should be used to store session IDs.
  400. * @see setUseCookies()
  401. */
  402. public function getUseCookies()
  403. {
  404. if (ini_get('session.use_cookies') === '0') {
  405. return false;
  406. } elseif (PHP_VERSION_ID >= 80400 || ini_get('session.use_only_cookies') === '1') {
  407. return true;
  408. }
  409. return null;
  410. }
  411. /**
  412. * Sets the value indicating whether cookies should be used to store session IDs.
  413. *
  414. * Three states are possible:
  415. *
  416. * - true: cookies and only cookies will be used to store session IDs.
  417. * - false: cookies will not be used to store session IDs.
  418. * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
  419. *
  420. * @param bool|null $value the value indicating whether cookies should be used to store session IDs.
  421. */
  422. public function setUseCookies($value)
  423. {
  424. $this->freeze();
  425. if ($value === false) {
  426. ini_set('session.use_cookies', '0');
  427. if (PHP_VERSION_ID < 80400) {
  428. ini_set('session.use_only_cookies', '0');
  429. }
  430. } elseif ($value === true) {
  431. ini_set('session.use_cookies', '1');
  432. if (PHP_VERSION_ID < 80400) {
  433. ini_set('session.use_only_cookies', '1');
  434. }
  435. } else {
  436. ini_set('session.use_cookies', '1');
  437. if (PHP_VERSION_ID < 80400) {
  438. ini_set('session.use_only_cookies', '0');
  439. }
  440. }
  441. $this->unfreeze();
  442. }
  443. /**
  444. * @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
  445. */
  446. public function getGCProbability()
  447. {
  448. return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
  449. }
  450. /**
  451. * @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
  452. * @throws InvalidArgumentException if the value is not between 0 and 100.
  453. */
  454. public function setGCProbability($value)
  455. {
  456. $this->freeze();
  457. if ($value >= 0 && $value <= 100) {
  458. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  459. ini_set('session.gc_probability', floor($value * 21474836.47));
  460. ini_set('session.gc_divisor', 2147483647);
  461. } else {
  462. throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
  463. }
  464. $this->unfreeze();
  465. }
  466. /**
  467. * @return bool whether transparent sid support is enabled or not, defaults to false.
  468. */
  469. public function getUseTransparentSessionID()
  470. {
  471. if (PHP_VERSION_ID < 80400) {
  472. return ini_get('session.use_trans_sid') == 1;
  473. }
  474. return false;
  475. }
  476. /**
  477. * @param bool $value whether transparent sid support is enabled or not.
  478. */
  479. public function setUseTransparentSessionID($value)
  480. {
  481. $this->freeze();
  482. if (PHP_VERSION_ID < 80400) {
  483. ini_set('session.use_trans_sid', $value ? '1' : '0');
  484. }
  485. $this->unfreeze();
  486. }
  487. /**
  488. * @return int the number of seconds after which data will be seen as 'garbage' and cleaned up.
  489. * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
  490. */
  491. public function getTimeout()
  492. {
  493. return (int) ini_get('session.gc_maxlifetime');
  494. }
  495. /**
  496. * @param int $value the number of seconds after which data will be seen as 'garbage' and cleaned up
  497. */
  498. public function setTimeout($value)
  499. {
  500. $this->freeze();
  501. ini_set('session.gc_maxlifetime', $value);
  502. $this->unfreeze();
  503. }
  504. /**
  505. * @param bool $value Whether strict mode is enabled or not.
  506. * When `true` this setting prevents the session component to use an uninitialized session ID.
  507. * Note: Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.
  508. * Warning! Although enabling strict mode is mandatory for secure sessions, the default value of 'session.use-strict-mode' is `0`.
  509. * @see https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode
  510. * @since 2.0.38
  511. */
  512. public function setUseStrictMode($value)
  513. {
  514. if (PHP_VERSION_ID < 50502) {
  515. if ($this->getUseCustomStorage() || !$value) {
  516. self::$_useStrictModePolyfill = $value;
  517. } else {
  518. throw new InvalidConfigException('Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.');
  519. }
  520. } else {
  521. $this->freeze();
  522. ini_set('session.use_strict_mode', $value ? '1' : '0');
  523. $this->unfreeze();
  524. }
  525. }
  526. /**
  527. * @return bool Whether strict mode is enabled or not.
  528. * @see setUseStrictMode()
  529. * @since 2.0.38
  530. */
  531. public function getUseStrictMode()
  532. {
  533. if (PHP_VERSION_ID < 50502) {
  534. return self::$_useStrictModePolyfill;
  535. }
  536. return (bool)ini_get('session.use_strict_mode');
  537. }
  538. /**
  539. * Session open handler.
  540. * This method should be overridden if [[useCustomStorage]] returns true.
  541. * @internal Do not call this method directly.
  542. * @param string $savePath session save path
  543. * @param string $sessionName session name
  544. * @return bool whether session is opened successfully
  545. */
  546. public function openSession($savePath, $sessionName)
  547. {
  548. return true;
  549. }
  550. /**
  551. * Session close handler.
  552. * This method should be overridden if [[useCustomStorage]] returns true.
  553. * @internal Do not call this method directly.
  554. * @return bool whether session is closed successfully
  555. */
  556. public function closeSession()
  557. {
  558. return true;
  559. }
  560. /**
  561. * Session read handler.
  562. * This method should be overridden if [[useCustomStorage]] returns true.
  563. * @internal Do not call this method directly.
  564. * @param string $id session ID
  565. * @return string|false the session data, or false on failure
  566. */
  567. public function readSession($id)
  568. {
  569. return '';
  570. }
  571. /**
  572. * Session write handler.
  573. * This method should be overridden if [[useCustomStorage]] returns true.
  574. * @internal Do not call this method directly.
  575. * @param string $id session ID
  576. * @param string $data session data
  577. * @return bool whether session write is successful
  578. */
  579. public function writeSession($id, $data)
  580. {
  581. return true;
  582. }
  583. /**
  584. * Session destroy handler.
  585. * This method should be overridden if [[useCustomStorage]] returns true.
  586. * @internal Do not call this method directly.
  587. * @param string $id session ID
  588. * @return bool whether session is destroyed successfully
  589. */
  590. public function destroySession($id)
  591. {
  592. return true;
  593. }
  594. /**
  595. * Session GC (garbage collection) handler.
  596. * This method should be overridden if [[useCustomStorage]] returns true.
  597. * @internal Do not call this method directly.
  598. * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  599. * @return int|false the number of deleted sessions on success, or false on failure
  600. */
  601. public function gcSession($maxLifetime)
  602. {
  603. return 0;
  604. }
  605. /**
  606. * Returns an iterator for traversing the session variables.
  607. * This method is required by the interface [[\IteratorAggregate]].
  608. * @return SessionIterator an iterator for traversing the session variables.
  609. */
  610. #[\ReturnTypeWillChange]
  611. public function getIterator()
  612. {
  613. $this->open();
  614. return new SessionIterator();
  615. }
  616. /**
  617. * Returns the number of items in the session.
  618. * @return int the number of session variables
  619. */
  620. public function getCount()
  621. {
  622. $this->open();
  623. return count($_SESSION);
  624. }
  625. /**
  626. * Returns the number of items in the session.
  627. * This method is required by [[\Countable]] interface.
  628. * @return int number of items in the session.
  629. */
  630. #[\ReturnTypeWillChange]
  631. public function count()
  632. {
  633. return $this->getCount();
  634. }
  635. /**
  636. * Returns the session variable value with the session variable name.
  637. * If the session variable does not exist, the `$defaultValue` will be returned.
  638. * @param string $key the session variable name
  639. * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
  640. * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
  641. */
  642. public function get($key, $defaultValue = null)
  643. {
  644. $this->open();
  645. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  646. }
  647. /**
  648. * Adds a session variable.
  649. * If the specified name already exists, the old value will be overwritten.
  650. * @param string $key session variable name
  651. * @param mixed $value session variable value
  652. */
  653. public function set($key, $value)
  654. {
  655. $this->open();
  656. $_SESSION[$key] = $value;
  657. }
  658. /**
  659. * Removes a session variable.
  660. * @param string $key the name of the session variable to be removed
  661. * @return mixed the removed value, null if no such session variable.
  662. */
  663. public function remove($key)
  664. {
  665. $this->open();
  666. if (isset($_SESSION[$key])) {
  667. $value = $_SESSION[$key];
  668. unset($_SESSION[$key]);
  669. return $value;
  670. }
  671. return null;
  672. }
  673. /**
  674. * Removes all session variables.
  675. */
  676. public function removeAll()
  677. {
  678. $this->open();
  679. foreach (array_keys($_SESSION) as $key) {
  680. unset($_SESSION[$key]);
  681. }
  682. }
  683. /**
  684. * @param mixed $key session variable name
  685. * @return bool whether there is the named session variable
  686. */
  687. public function has($key)
  688. {
  689. $this->open();
  690. return isset($_SESSION[$key]);
  691. }
  692. /**
  693. * Updates the counters for flash messages and removes outdated flash messages.
  694. * This method should only be called once in [[init()]].
  695. */
  696. protected function updateFlashCounters()
  697. {
  698. $counters = $this->get($this->flashParam, []);
  699. if (is_array($counters)) {
  700. foreach ($counters as $key => $count) {
  701. if ($count > 0) {
  702. unset($counters[$key], $_SESSION[$key]);
  703. } elseif ($count == 0) {
  704. $counters[$key]++;
  705. }
  706. }
  707. $_SESSION[$this->flashParam] = $counters;
  708. } else {
  709. // fix the unexpected problem that flashParam doesn't return an array
  710. unset($_SESSION[$this->flashParam]);
  711. }
  712. }
  713. /**
  714. * Returns a flash message.
  715. * @param string $key the key identifying the flash message
  716. * @param mixed $defaultValue value to be returned if the flash message does not exist.
  717. * @param bool $delete whether to delete this flash message right after this method is called.
  718. * If false, the flash message will be automatically deleted in the next request.
  719. * @return mixed the flash message or an array of messages if addFlash was used
  720. * @see setFlash()
  721. * @see addFlash()
  722. * @see hasFlash()
  723. * @see getAllFlashes()
  724. * @see removeFlash()
  725. */
  726. public function getFlash($key, $defaultValue = null, $delete = false)
  727. {
  728. $counters = $this->get($this->flashParam, []);
  729. if (isset($counters[$key])) {
  730. $value = $this->get($key, $defaultValue);
  731. if ($delete) {
  732. $this->removeFlash($key);
  733. } elseif ($counters[$key] < 0) {
  734. // mark for deletion in the next request
  735. $counters[$key] = 1;
  736. $_SESSION[$this->flashParam] = $counters;
  737. }
  738. return $value;
  739. }
  740. return $defaultValue;
  741. }
  742. /**
  743. * Returns all flash messages.
  744. *
  745. * You may use this method to display all the flash messages in a view file:
  746. *
  747. * ```php
  748. * <?php
  749. * foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
  750. * echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
  751. * } ?>
  752. * ```
  753. *
  754. * With the above code you can use the [bootstrap alert][] classes such as `success`, `info`, `danger`
  755. * as the flash message key to influence the color of the div.
  756. *
  757. * Note that if you use [[addFlash()]], `$message` will be an array, and you will have to adjust the above code.
  758. *
  759. * [bootstrap alert]: https://getbootstrap.com/docs/3.4/components/#alerts
  760. *
  761. * @param bool $delete whether to delete the flash messages right after this method is called.
  762. * If false, the flash messages will be automatically deleted in the next request.
  763. * @return array flash messages (key => message or key => [message1, message2]).
  764. * @see setFlash()
  765. * @see addFlash()
  766. * @see getFlash()
  767. * @see hasFlash()
  768. * @see removeFlash()
  769. */
  770. public function getAllFlashes($delete = false)
  771. {
  772. $counters = $this->get($this->flashParam, []);
  773. $flashes = [];
  774. foreach (array_keys($counters) as $key) {
  775. if (array_key_exists($key, $_SESSION)) {
  776. $flashes[$key] = $_SESSION[$key];
  777. if ($delete) {
  778. unset($counters[$key], $_SESSION[$key]);
  779. } elseif ($counters[$key] < 0) {
  780. // mark for deletion in the next request
  781. $counters[$key] = 1;
  782. }
  783. } else {
  784. unset($counters[$key]);
  785. }
  786. }
  787. $_SESSION[$this->flashParam] = $counters;
  788. return $flashes;
  789. }
  790. /**
  791. * Sets a flash message.
  792. * A flash message will be automatically deleted after it is accessed in a request and the deletion will happen
  793. * in the next request.
  794. * If there is already an existing flash message with the same key, it will be overwritten by the new one.
  795. * @param string $key the key identifying the flash message. Note that flash messages
  796. * and normal session variables share the same name space. If you have a normal
  797. * session variable using the same name, its value will be overwritten by this method.
  798. * @param mixed $value flash message
  799. * @param bool $removeAfterAccess whether the flash message should be automatically removed only if
  800. * it is accessed. If false, the flash message will be automatically removed after the next request,
  801. * regardless if it is accessed or not. If true (default value), the flash message will remain until after
  802. * it is accessed.
  803. * @see getFlash()
  804. * @see addFlash()
  805. * @see removeFlash()
  806. */
  807. public function setFlash($key, $value = true, $removeAfterAccess = true)
  808. {
  809. $counters = $this->get($this->flashParam, []);
  810. $counters[$key] = $removeAfterAccess ? -1 : 0;
  811. $_SESSION[$key] = $value;
  812. $_SESSION[$this->flashParam] = $counters;
  813. }
  814. /**
  815. * Adds a flash message.
  816. * If there are existing flash messages with the same key, the new one will be appended to the existing message array.
  817. * @param string $key the key identifying the flash message.
  818. * @param mixed $value flash message
  819. * @param bool $removeAfterAccess whether the flash message should be automatically removed only if
  820. * it is accessed. If false, the flash message will be automatically removed after the next request,
  821. * regardless if it is accessed or not. If true (default value), the flash message will remain until after
  822. * it is accessed.
  823. * @see getFlash()
  824. * @see setFlash()
  825. * @see removeFlash()
  826. */
  827. public function addFlash($key, $value = true, $removeAfterAccess = true)
  828. {
  829. $counters = $this->get($this->flashParam, []);
  830. $counters[$key] = $removeAfterAccess ? -1 : 0;
  831. $_SESSION[$this->flashParam] = $counters;
  832. if (empty($_SESSION[$key])) {
  833. $_SESSION[$key] = [$value];
  834. } elseif (is_array($_SESSION[$key])) {
  835. $_SESSION[$key][] = $value;
  836. } else {
  837. $_SESSION[$key] = [$_SESSION[$key], $value];
  838. }
  839. }
  840. /**
  841. * Removes a flash message.
  842. * @param string $key the key identifying the flash message. Note that flash messages
  843. * and normal session variables share the same name space. If you have a normal
  844. * session variable using the same name, it will be removed by this method.
  845. * @return mixed the removed flash message. Null if the flash message does not exist.
  846. * @see getFlash()
  847. * @see setFlash()
  848. * @see addFlash()
  849. * @see removeAllFlashes()
  850. */
  851. public function removeFlash($key)
  852. {
  853. $counters = $this->get($this->flashParam, []);
  854. $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
  855. unset($counters[$key], $_SESSION[$key]);
  856. $_SESSION[$this->flashParam] = $counters;
  857. return $value;
  858. }
  859. /**
  860. * Removes all flash messages.
  861. * Note that flash messages and normal session variables share the same name space.
  862. * If you have a normal session variable using the same name, it will be removed
  863. * by this method.
  864. * @see getFlash()
  865. * @see setFlash()
  866. * @see addFlash()
  867. * @see removeFlash()
  868. */
  869. public function removeAllFlashes()
  870. {
  871. $counters = $this->get($this->flashParam, []);
  872. foreach (array_keys($counters) as $key) {
  873. unset($_SESSION[$key]);
  874. }
  875. unset($_SESSION[$this->flashParam]);
  876. }
  877. /**
  878. * Returns a value indicating whether there are flash messages associated with the specified key.
  879. * @param string $key key identifying the flash message type
  880. * @return bool whether any flash messages exist under specified key
  881. */
  882. public function hasFlash($key)
  883. {
  884. return $this->getFlash($key) !== null;
  885. }
  886. /**
  887. * This method is required by the interface [[\ArrayAccess]].
  888. * @param int|string $offset the offset to check on
  889. * @return bool
  890. */
  891. #[\ReturnTypeWillChange]
  892. public function offsetExists($offset)
  893. {
  894. $this->open();
  895. return isset($_SESSION[$offset]);
  896. }
  897. /**
  898. * This method is required by the interface [[\ArrayAccess]].
  899. * @param int|string $offset the offset to retrieve element.
  900. * @return mixed the element at the offset, null if no element is found at the offset
  901. */
  902. #[\ReturnTypeWillChange]
  903. public function offsetGet($offset)
  904. {
  905. $this->open();
  906. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  907. }
  908. /**
  909. * This method is required by the interface [[\ArrayAccess]].
  910. * @param int|string $offset the offset to set element
  911. * @param mixed $item the element value
  912. */
  913. #[\ReturnTypeWillChange]
  914. public function offsetSet($offset, $item)
  915. {
  916. $this->open();
  917. $_SESSION[$offset] = $item;
  918. }
  919. /**
  920. * This method is required by the interface [[\ArrayAccess]].
  921. * @param int|string $offset the offset to unset element
  922. */
  923. #[\ReturnTypeWillChange]
  924. public function offsetUnset($offset)
  925. {
  926. $this->open();
  927. unset($_SESSION[$offset]);
  928. }
  929. /**
  930. * If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception.
  931. * This function saves session data to temporary variable and stop session.
  932. * @since 2.0.14
  933. */
  934. protected function freeze()
  935. {
  936. if ($this->getIsActive()) {
  937. if (isset($_SESSION)) {
  938. $this->_frozenSessionData = $_SESSION;
  939. }
  940. $this->close();
  941. Yii::info('Session frozen', __METHOD__);
  942. }
  943. }
  944. /**
  945. * Starts session and restores data from temporary variable
  946. * @since 2.0.14
  947. */
  948. protected function unfreeze()
  949. {
  950. if (null !== $this->_frozenSessionData) {
  951. YII_DEBUG ? session_start() : @session_start();
  952. if ($this->getIsActive()) {
  953. Yii::info('Session unfrozen', __METHOD__);
  954. } else {
  955. $error = error_get_last();
  956. $message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
  957. Yii::error($message, __METHOD__);
  958. }
  959. $_SESSION = $this->_frozenSessionData;
  960. $this->_frozenSessionData = null;
  961. }
  962. }
  963. /**
  964. * Set cache limiter
  965. *
  966. * @param string $cacheLimiter
  967. * @since 2.0.14
  968. */
  969. public function setCacheLimiter($cacheLimiter)
  970. {
  971. $this->freeze();
  972. session_cache_limiter($cacheLimiter);
  973. $this->unfreeze();
  974. }
  975. /**
  976. * Returns current cache limiter
  977. *
  978. * @return string current cache limiter
  979. * @since 2.0.14
  980. */
  981. public function getCacheLimiter()
  982. {
  983. return session_cache_limiter();
  984. }
  985. }