Session.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\InvalidParamException;
  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 array $allFlashes Flash messages (key => message or key => [message1, message2]). This property
  46. * is read-only.
  47. * @property array $cookieParams The session cookie parameters. This property is read-only.
  48. * @property int $count The number of session variables. This property is read-only.
  49. * @property string $flash The key identifying the flash message. Note that flash messages and normal session
  50. * variables share the same name space. If you have a normal session variable using the same name, its value will
  51. * be overwritten by this method. This property is write-only.
  52. * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
  53. * started on every session initialization, defaults to 1 meaning 1% chance.
  54. * @property bool $hasSessionId Whether the current request has sent the session ID.
  55. * @property string $id The current session ID.
  56. * @property bool $isActive Whether the session has started. This property is read-only.
  57. * @property SessionIterator $iterator An iterator for traversing the session variables. This property is
  58. * read-only.
  59. * @property string $name The current session name.
  60. * @property string $savePath The current session save path, defaults to '/tmp'.
  61. * @property int $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. The
  62. * default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
  63. * @property bool|null $useCookies The value indicating whether cookies should be used to store session IDs.
  64. * @property bool $useCustomStorage Whether to use custom storage. This property is read-only.
  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 the name of the session variable that stores the flash message data.
  75. */
  76. public $flashParam = '__flash';
  77. /**
  78. * @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.
  79. */
  80. public $handler;
  81. /**
  82. * @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
  83. * Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
  84. * @see http://www.php.net/manual/en/function.session-set-cookie-params.php
  85. */
  86. private $_cookieParams = ['httponly' => true];
  87. /**
  88. * Initializes the application component.
  89. * This method is required by IApplicationComponent and is invoked by application.
  90. */
  91. public function init()
  92. {
  93. parent::init();
  94. register_shutdown_function([$this, 'close']);
  95. if ($this->getIsActive()) {
  96. Yii::warning('Session is already started', __METHOD__);
  97. $this->updateFlashCounters();
  98. }
  99. }
  100. /**
  101. * Returns a value indicating whether to use custom session storage.
  102. * This method should be overridden to return true by child classes that implement custom session storage.
  103. * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
  104. * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
  105. * @return bool whether to use custom storage.
  106. */
  107. public function getUseCustomStorage()
  108. {
  109. return false;
  110. }
  111. /**
  112. * Starts the session.
  113. */
  114. public function open()
  115. {
  116. if ($this->getIsActive()) {
  117. return;
  118. }
  119. $this->registerSessionHandler();
  120. $this->setCookieParamsInternal();
  121. @session_start();
  122. if ($this->getIsActive()) {
  123. Yii::info('Session started', __METHOD__);
  124. $this->updateFlashCounters();
  125. } else {
  126. $error = error_get_last();
  127. $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
  128. Yii::error($message, __METHOD__);
  129. }
  130. }
  131. /**
  132. * Registers session handler.
  133. * @throws \yii\base\InvalidConfigException
  134. */
  135. protected function registerSessionHandler()
  136. {
  137. if ($this->handler !== null) {
  138. if (!is_object($this->handler)) {
  139. $this->handler = Yii::createObject($this->handler);
  140. }
  141. if (!$this->handler instanceof \SessionHandlerInterface) {
  142. throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
  143. }
  144. YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
  145. } elseif ($this->getUseCustomStorage()) {
  146. if (YII_DEBUG) {
  147. session_set_save_handler(
  148. [$this, 'openSession'],
  149. [$this, 'closeSession'],
  150. [$this, 'readSession'],
  151. [$this, 'writeSession'],
  152. [$this, 'destroySession'],
  153. [$this, 'gcSession']
  154. );
  155. } else {
  156. @session_set_save_handler(
  157. [$this, 'openSession'],
  158. [$this, 'closeSession'],
  159. [$this, 'readSession'],
  160. [$this, 'writeSession'],
  161. [$this, 'destroySession'],
  162. [$this, 'gcSession']
  163. );
  164. }
  165. }
  166. }
  167. /**
  168. * Ends the current session and store session data.
  169. */
  170. public function close()
  171. {
  172. if ($this->getIsActive()) {
  173. YII_DEBUG ? session_write_close() : @session_write_close();
  174. }
  175. }
  176. /**
  177. * Frees all session variables and destroys all data registered to a session.
  178. *
  179. * This method has no effect when session is not [[getIsActive()|active]].
  180. * Make sure to call [[open()]] before calling it.
  181. * @see open()
  182. * @see isActive
  183. */
  184. public function destroy()
  185. {
  186. if ($this->getIsActive()) {
  187. $sessionId = session_id();
  188. $this->close();
  189. $this->setId($sessionId);
  190. $this->open();
  191. session_unset();
  192. session_destroy();
  193. $this->setId($sessionId);
  194. }
  195. }
  196. /**
  197. * @return bool whether the session has started
  198. */
  199. public function getIsActive()
  200. {
  201. return session_status() === PHP_SESSION_ACTIVE;
  202. }
  203. private $_hasSessionId;
  204. /**
  205. * Returns a value indicating whether the current request has sent the session ID.
  206. * The default implementation will check cookie and $_GET using the session name.
  207. * If you send session ID via other ways, you may need to override this method
  208. * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
  209. * @return bool whether the current request has sent the session ID.
  210. */
  211. public function getHasSessionId()
  212. {
  213. if ($this->_hasSessionId === null) {
  214. $name = $this->getName();
  215. $request = Yii::$app->getRequest();
  216. if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
  217. $this->_hasSessionId = true;
  218. } elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
  219. $this->_hasSessionId = $request->get($name) != '';
  220. } else {
  221. $this->_hasSessionId = false;
  222. }
  223. }
  224. return $this->_hasSessionId;
  225. }
  226. /**
  227. * Sets the value indicating whether the current request has sent the session ID.
  228. * This method is provided so that you can override the default way of determining
  229. * whether the session ID is sent.
  230. * @param bool $value whether the current request has sent the session ID.
  231. */
  232. public function setHasSessionId($value)
  233. {
  234. $this->_hasSessionId = $value;
  235. }
  236. /**
  237. * Gets the session ID.
  238. * This is a wrapper for [PHP session_id()](http://php.net/manual/en/function.session-id.php).
  239. * @return string the current session ID
  240. */
  241. public function getId()
  242. {
  243. return session_id();
  244. }
  245. /**
  246. * Sets the session ID.
  247. * This is a wrapper for [PHP session_id()](http://php.net/manual/en/function.session-id.php).
  248. * @param string $value the session ID for the current session
  249. */
  250. public function setId($value)
  251. {
  252. session_id($value);
  253. }
  254. /**
  255. * Updates the current session ID with a newly generated one.
  256. *
  257. * Please refer to <http://php.net/session_regenerate_id> for more details.
  258. *
  259. * This method has no effect when session is not [[getIsActive()|active]].
  260. * Make sure to call [[open()]] before calling it.
  261. *
  262. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  263. * @see open()
  264. * @see isActive
  265. */
  266. public function regenerateID($deleteOldSession = false)
  267. {
  268. if ($this->getIsActive()) {
  269. // add @ to inhibit possible warning due to race condition
  270. // https://github.com/yiisoft/yii2/pull/1812
  271. if (YII_DEBUG && !headers_sent()) {
  272. session_regenerate_id($deleteOldSession);
  273. } else {
  274. @session_regenerate_id($deleteOldSession);
  275. }
  276. }
  277. }
  278. /**
  279. * Gets the name of the current session.
  280. * This is a wrapper for [PHP session_name()](http://php.net/manual/en/function.session-name.php).
  281. * @return string the current session name
  282. */
  283. public function getName()
  284. {
  285. return session_name();
  286. }
  287. /**
  288. * Sets the name for the current session.
  289. * This is a wrapper for [PHP session_name()](http://php.net/manual/en/function.session-name.php).
  290. * @param string $value the session name for the current session, must be an alphanumeric string.
  291. * It defaults to "PHPSESSID".
  292. */
  293. public function setName($value)
  294. {
  295. session_name($value);
  296. }
  297. /**
  298. * Gets the current session save path.
  299. * This is a wrapper for [PHP session_save_path()](http://php.net/manual/en/function.session-save-path.php).
  300. * @return string the current session save path, defaults to '/tmp'.
  301. */
  302. public function getSavePath()
  303. {
  304. return session_save_path();
  305. }
  306. /**
  307. * Sets the current session save path.
  308. * This is a wrapper for [PHP session_save_path()](http://php.net/manual/en/function.session-save-path.php).
  309. * @param string $value the current session save path. This can be either a directory name or a [path alias](guide:concept-aliases).
  310. * @throws InvalidParamException if the path is not a valid directory
  311. */
  312. public function setSavePath($value)
  313. {
  314. $path = Yii::getAlias($value);
  315. if (is_dir($path)) {
  316. session_save_path($path);
  317. } else {
  318. throw new InvalidParamException("Session save path is not a valid directory: $value");
  319. }
  320. }
  321. /**
  322. * @return array the session cookie parameters.
  323. * @see http://php.net/manual/en/function.session-get-cookie-params.php
  324. */
  325. public function getCookieParams()
  326. {
  327. return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
  328. }
  329. /**
  330. * Sets the session cookie parameters.
  331. * The cookie parameters passed to this method will be merged with the result
  332. * of `session_get_cookie_params()`.
  333. * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httponly`.
  334. * @throws InvalidParamException if the parameters are incomplete.
  335. * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
  336. */
  337. public function setCookieParams(array $value)
  338. {
  339. $this->_cookieParams = $value;
  340. }
  341. /**
  342. * Sets the session cookie parameters.
  343. * This method is called by [[open()]] when it is about to open the session.
  344. * @throws InvalidParamException if the parameters are incomplete.
  345. * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
  346. */
  347. private function setCookieParamsInternal()
  348. {
  349. $data = $this->getCookieParams();
  350. if (isset($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly'])) {
  351. session_set_cookie_params($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly']);
  352. } else {
  353. throw new InvalidParamException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.');
  354. }
  355. }
  356. /**
  357. * Returns the value indicating whether cookies should be used to store session IDs.
  358. * @return bool|null the value indicating whether cookies should be used to store session IDs.
  359. * @see setUseCookies()
  360. */
  361. public function getUseCookies()
  362. {
  363. if (ini_get('session.use_cookies') === '0') {
  364. return false;
  365. } elseif (ini_get('session.use_only_cookies') === '1') {
  366. return true;
  367. } else {
  368. return null;
  369. }
  370. }
  371. /**
  372. * Sets the value indicating whether cookies should be used to store session IDs.
  373. * Three states are possible:
  374. *
  375. * - true: cookies and only cookies will be used to store session IDs.
  376. * - false: cookies will not be used to store session IDs.
  377. * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
  378. *
  379. * @param bool|null $value the value indicating whether cookies should be used to store session IDs.
  380. */
  381. public function setUseCookies($value)
  382. {
  383. if ($value === false) {
  384. ini_set('session.use_cookies', '0');
  385. ini_set('session.use_only_cookies', '0');
  386. } elseif ($value === true) {
  387. ini_set('session.use_cookies', '1');
  388. ini_set('session.use_only_cookies', '1');
  389. } else {
  390. ini_set('session.use_cookies', '1');
  391. ini_set('session.use_only_cookies', '0');
  392. }
  393. }
  394. /**
  395. * @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
  396. */
  397. public function getGCProbability()
  398. {
  399. return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
  400. }
  401. /**
  402. * @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
  403. * @throws InvalidParamException if the value is not between 0 and 100.
  404. */
  405. public function setGCProbability($value)
  406. {
  407. if ($value >= 0 && $value <= 100) {
  408. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  409. ini_set('session.gc_probability', floor($value * 21474836.47));
  410. ini_set('session.gc_divisor', 2147483647);
  411. } else {
  412. throw new InvalidParamException('GCProbability must be a value between 0 and 100.');
  413. }
  414. }
  415. /**
  416. * @return bool whether transparent sid support is enabled or not, defaults to false.
  417. */
  418. public function getUseTransparentSessionID()
  419. {
  420. return ini_get('session.use_trans_sid') == 1;
  421. }
  422. /**
  423. * @param bool $value whether transparent sid support is enabled or not.
  424. */
  425. public function setUseTransparentSessionID($value)
  426. {
  427. ini_set('session.use_trans_sid', $value ? '1' : '0');
  428. }
  429. /**
  430. * @return int the number of seconds after which data will be seen as 'garbage' and cleaned up.
  431. * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
  432. */
  433. public function getTimeout()
  434. {
  435. return (int) ini_get('session.gc_maxlifetime');
  436. }
  437. /**
  438. * @param int $value the number of seconds after which data will be seen as 'garbage' and cleaned up
  439. */
  440. public function setTimeout($value)
  441. {
  442. ini_set('session.gc_maxlifetime', $value);
  443. }
  444. /**
  445. * Session open handler.
  446. * This method should be overridden if [[useCustomStorage]] returns true.
  447. * @internal Do not call this method directly.
  448. * @param string $savePath session save path
  449. * @param string $sessionName session name
  450. * @return bool whether session is opened successfully
  451. */
  452. public function openSession($savePath, $sessionName)
  453. {
  454. return true;
  455. }
  456. /**
  457. * Session close handler.
  458. * This method should be overridden if [[useCustomStorage]] returns true.
  459. * @internal Do not call this method directly.
  460. * @return bool whether session is closed successfully
  461. */
  462. public function closeSession()
  463. {
  464. return true;
  465. }
  466. /**
  467. * Session read handler.
  468. * This method should be overridden if [[useCustomStorage]] returns true.
  469. * @internal Do not call this method directly.
  470. * @param string $id session ID
  471. * @return string the session data
  472. */
  473. public function readSession($id)
  474. {
  475. return '';
  476. }
  477. /**
  478. * Session write handler.
  479. * This method should be overridden if [[useCustomStorage]] returns true.
  480. * @internal Do not call this method directly.
  481. * @param string $id session ID
  482. * @param string $data session data
  483. * @return bool whether session write is successful
  484. */
  485. public function writeSession($id, $data)
  486. {
  487. return true;
  488. }
  489. /**
  490. * Session destroy handler.
  491. * This method should be overridden if [[useCustomStorage]] returns true.
  492. * @internal Do not call this method directly.
  493. * @param string $id session ID
  494. * @return bool whether session is destroyed successfully
  495. */
  496. public function destroySession($id)
  497. {
  498. return true;
  499. }
  500. /**
  501. * Session GC (garbage collection) handler.
  502. * This method should be overridden if [[useCustomStorage]] returns true.
  503. * @internal Do not call this method directly.
  504. * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  505. * @return bool whether session is GCed successfully
  506. */
  507. public function gcSession($maxLifetime)
  508. {
  509. return true;
  510. }
  511. /**
  512. * Returns an iterator for traversing the session variables.
  513. * This method is required by the interface [[\IteratorAggregate]].
  514. * @return SessionIterator an iterator for traversing the session variables.
  515. */
  516. public function getIterator()
  517. {
  518. $this->open();
  519. return new SessionIterator;
  520. }
  521. /**
  522. * Returns the number of items in the session.
  523. * @return int the number of session variables
  524. */
  525. public function getCount()
  526. {
  527. $this->open();
  528. return count($_SESSION);
  529. }
  530. /**
  531. * Returns the number of items in the session.
  532. * This method is required by [[\Countable]] interface.
  533. * @return int number of items in the session.
  534. */
  535. public function count()
  536. {
  537. return $this->getCount();
  538. }
  539. /**
  540. * Returns the session variable value with the session variable name.
  541. * If the session variable does not exist, the `$defaultValue` will be returned.
  542. * @param string $key the session variable name
  543. * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
  544. * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
  545. */
  546. public function get($key, $defaultValue = null)
  547. {
  548. $this->open();
  549. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  550. }
  551. /**
  552. * Adds a session variable.
  553. * If the specified name already exists, the old value will be overwritten.
  554. * @param string $key session variable name
  555. * @param mixed $value session variable value
  556. */
  557. public function set($key, $value)
  558. {
  559. $this->open();
  560. $_SESSION[$key] = $value;
  561. }
  562. /**
  563. * Removes a session variable.
  564. * @param string $key the name of the session variable to be removed
  565. * @return mixed the removed value, null if no such session variable.
  566. */
  567. public function remove($key)
  568. {
  569. $this->open();
  570. if (isset($_SESSION[$key])) {
  571. $value = $_SESSION[$key];
  572. unset($_SESSION[$key]);
  573. return $value;
  574. } else {
  575. return null;
  576. }
  577. }
  578. /**
  579. * Removes all session variables
  580. */
  581. public function removeAll()
  582. {
  583. $this->open();
  584. foreach (array_keys($_SESSION) as $key) {
  585. unset($_SESSION[$key]);
  586. }
  587. }
  588. /**
  589. * @param mixed $key session variable name
  590. * @return bool whether there is the named session variable
  591. */
  592. public function has($key)
  593. {
  594. $this->open();
  595. return isset($_SESSION[$key]);
  596. }
  597. /**
  598. * Updates the counters for flash messages and removes outdated flash messages.
  599. * This method should only be called once in [[init()]].
  600. */
  601. protected function updateFlashCounters()
  602. {
  603. $counters = $this->get($this->flashParam, []);
  604. if (is_array($counters)) {
  605. foreach ($counters as $key => $count) {
  606. if ($count > 0) {
  607. unset($counters[$key], $_SESSION[$key]);
  608. } elseif ($count == 0) {
  609. $counters[$key]++;
  610. }
  611. }
  612. $_SESSION[$this->flashParam] = $counters;
  613. } else {
  614. // fix the unexpected problem that flashParam doesn't return an array
  615. unset($_SESSION[$this->flashParam]);
  616. }
  617. }
  618. /**
  619. * Returns a flash message.
  620. * @param string $key the key identifying the flash message
  621. * @param mixed $defaultValue value to be returned if the flash message does not exist.
  622. * @param bool $delete whether to delete this flash message right after this method is called.
  623. * If false, the flash message will be automatically deleted in the next request.
  624. * @return mixed the flash message or an array of messages if addFlash was used
  625. * @see setFlash()
  626. * @see addFlash()
  627. * @see hasFlash()
  628. * @see getAllFlashes()
  629. * @see removeFlash()
  630. */
  631. public function getFlash($key, $defaultValue = null, $delete = false)
  632. {
  633. $counters = $this->get($this->flashParam, []);
  634. if (isset($counters[$key])) {
  635. $value = $this->get($key, $defaultValue);
  636. if ($delete) {
  637. $this->removeFlash($key);
  638. } elseif ($counters[$key] < 0) {
  639. // mark for deletion in the next request
  640. $counters[$key] = 1;
  641. $_SESSION[$this->flashParam] = $counters;
  642. }
  643. return $value;
  644. } else {
  645. return $defaultValue;
  646. }
  647. }
  648. /**
  649. * Returns all flash messages.
  650. *
  651. * You may use this method to display all the flash messages in a view file:
  652. *
  653. * ```php
  654. * <?php
  655. * foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
  656. * echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
  657. * } ?>
  658. * ```
  659. *
  660. * With the above code you can use the [bootstrap alert][] classes such as `success`, `info`, `danger`
  661. * as the flash message key to influence the color of the div.
  662. *
  663. * Note that if you use [[addFlash()]], `$message` will be an array, and you will have to adjust the above code.
  664. *
  665. * [bootstrap alert]: http://getbootstrap.com/components/#alerts
  666. *
  667. * @param bool $delete whether to delete the flash messages right after this method is called.
  668. * If false, the flash messages will be automatically deleted in the next request.
  669. * @return array flash messages (key => message or key => [message1, message2]).
  670. * @see setFlash()
  671. * @see addFlash()
  672. * @see getFlash()
  673. * @see hasFlash()
  674. * @see removeFlash()
  675. */
  676. public function getAllFlashes($delete = false)
  677. {
  678. $counters = $this->get($this->flashParam, []);
  679. $flashes = [];
  680. foreach (array_keys($counters) as $key) {
  681. if (array_key_exists($key, $_SESSION)) {
  682. $flashes[$key] = $_SESSION[$key];
  683. if ($delete) {
  684. unset($counters[$key], $_SESSION[$key]);
  685. } elseif ($counters[$key] < 0) {
  686. // mark for deletion in the next request
  687. $counters[$key] = 1;
  688. }
  689. } else {
  690. unset($counters[$key]);
  691. }
  692. }
  693. $_SESSION[$this->flashParam] = $counters;
  694. return $flashes;
  695. }
  696. /**
  697. * Sets a flash message.
  698. * A flash message will be automatically deleted after it is accessed in a request and the deletion will happen
  699. * in the next request.
  700. * If there is already an existing flash message with the same key, it will be overwritten by the new one.
  701. * @param string $key the key identifying the flash message. Note that flash messages
  702. * and normal session variables share the same name space. If you have a normal
  703. * session variable using the same name, its value will be overwritten by this method.
  704. * @param mixed $value flash message
  705. * @param bool $removeAfterAccess whether the flash message should be automatically removed only if
  706. * it is accessed. If false, the flash message will be automatically removed after the next request,
  707. * regardless if it is accessed or not. If true (default value), the flash message will remain until after
  708. * it is accessed.
  709. * @see getFlash()
  710. * @see addFlash()
  711. * @see removeFlash()
  712. */
  713. public function setFlash($key, $value = true, $removeAfterAccess = true)
  714. {
  715. $counters = $this->get($this->flashParam, []);
  716. $counters[$key] = $removeAfterAccess ? -1 : 0;
  717. $_SESSION[$key] = $value;
  718. $_SESSION[$this->flashParam] = $counters;
  719. }
  720. /**
  721. * Adds a flash message.
  722. * If there are existing flash messages with the same key, the new one will be appended to the existing message array.
  723. * @param string $key the key identifying the flash message.
  724. * @param mixed $value flash message
  725. * @param bool $removeAfterAccess whether the flash message should be automatically removed only if
  726. * it is accessed. If false, the flash message will be automatically removed after the next request,
  727. * regardless if it is accessed or not. If true (default value), the flash message will remain until after
  728. * it is accessed.
  729. * @see getFlash()
  730. * @see setFlash()
  731. * @see removeFlash()
  732. */
  733. public function addFlash($key, $value = true, $removeAfterAccess = true)
  734. {
  735. $counters = $this->get($this->flashParam, []);
  736. $counters[$key] = $removeAfterAccess ? -1 : 0;
  737. $_SESSION[$this->flashParam] = $counters;
  738. if (empty($_SESSION[$key])) {
  739. $_SESSION[$key] = [$value];
  740. } else {
  741. if (is_array($_SESSION[$key])) {
  742. $_SESSION[$key][] = $value;
  743. } else {
  744. $_SESSION[$key] = [$_SESSION[$key], $value];
  745. }
  746. }
  747. }
  748. /**
  749. * Removes a flash message.
  750. * @param string $key the key identifying the flash message. Note that flash messages
  751. * and normal session variables share the same name space. If you have a normal
  752. * session variable using the same name, it will be removed by this method.
  753. * @return mixed the removed flash message. Null if the flash message does not exist.
  754. * @see getFlash()
  755. * @see setFlash()
  756. * @see addFlash()
  757. * @see removeAllFlashes()
  758. */
  759. public function removeFlash($key)
  760. {
  761. $counters = $this->get($this->flashParam, []);
  762. $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
  763. unset($counters[$key], $_SESSION[$key]);
  764. $_SESSION[$this->flashParam] = $counters;
  765. return $value;
  766. }
  767. /**
  768. * Removes all flash messages.
  769. * Note that flash messages and normal session variables share the same name space.
  770. * If you have a normal session variable using the same name, it will be removed
  771. * by this method.
  772. * @see getFlash()
  773. * @see setFlash()
  774. * @see addFlash()
  775. * @see removeFlash()
  776. */
  777. public function removeAllFlashes()
  778. {
  779. $counters = $this->get($this->flashParam, []);
  780. foreach (array_keys($counters) as $key) {
  781. unset($_SESSION[$key]);
  782. }
  783. unset($_SESSION[$this->flashParam]);
  784. }
  785. /**
  786. * Returns a value indicating whether there are flash messages associated with the specified key.
  787. * @param string $key key identifying the flash message type
  788. * @return bool whether any flash messages exist under specified key
  789. */
  790. public function hasFlash($key)
  791. {
  792. return $this->getFlash($key) !== null;
  793. }
  794. /**
  795. * This method is required by the interface [[\ArrayAccess]].
  796. * @param mixed $offset the offset to check on
  797. * @return bool
  798. */
  799. public function offsetExists($offset)
  800. {
  801. $this->open();
  802. return isset($_SESSION[$offset]);
  803. }
  804. /**
  805. * This method is required by the interface [[\ArrayAccess]].
  806. * @param int $offset the offset to retrieve element.
  807. * @return mixed the element at the offset, null if no element is found at the offset
  808. */
  809. public function offsetGet($offset)
  810. {
  811. $this->open();
  812. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  813. }
  814. /**
  815. * This method is required by the interface [[\ArrayAccess]].
  816. * @param int $offset the offset to set element
  817. * @param mixed $item the element value
  818. */
  819. public function offsetSet($offset, $item)
  820. {
  821. $this->open();
  822. $_SESSION[$offset] = $item;
  823. }
  824. /**
  825. * This method is required by the interface [[\ArrayAccess]].
  826. * @param mixed $offset the offset to unset element
  827. */
  828. public function offsetUnset($offset)
  829. {
  830. $this->open();
  831. unset($_SESSION[$offset]);
  832. }
  833. }