CHttpSession.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. <?php
  2. /**
  3. * CHttpSession class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CHttpSession provides session-level data management and the related configurations.
  12. *
  13. * To start the session, call {@link open()}; To complete and send out session data, call {@link close()};
  14. * To destroy the session, call {@link destroy()}.
  15. *
  16. * If {@link autoStart} is set true, the session will be started automatically
  17. * when the application component is initialized by the application.
  18. *
  19. * CHttpSession can be used like an array to set and get session data. For example,
  20. * <pre>
  21. * $session=new CHttpSession;
  22. * $session->open();
  23. * $value1=$session['name1']; // get session variable 'name1'
  24. * $value2=$session['name2']; // get session variable 'name2'
  25. * foreach($session as $name=>$value) // traverse all session variables
  26. * $session['name3']=$value3; // set session variable 'name3'
  27. * </pre>
  28. *
  29. * The following configurations are available for session:
  30. * <ul>
  31. * <li>{@link setSessionID sessionID};</li>
  32. * <li>{@link setSessionName sessionName};</li>
  33. * <li>{@link autoStart};</li>
  34. * <li>{@link setSavePath savePath};</li>
  35. * <li>{@link setCookieParams cookieParams};</li>
  36. * <li>{@link setGCProbability gcProbability};</li>
  37. * <li>{@link setCookieMode cookieMode};</li>
  38. * <li>{@link setUseTransparentSessionID useTransparentSessionID};</li>
  39. * <li>{@link setTimeout timeout}.</li>
  40. * </ul>
  41. * See the corresponding setter and getter documentation for more information.
  42. * Note, these properties must be set before the session is started.
  43. *
  44. * CHttpSession can be extended to support customized session storage.
  45. * Override {@link openSession}, {@link closeSession}, {@link readSession},
  46. * {@link writeSession}, {@link destroySession} and {@link gcSession}
  47. * and set {@link useCustomStorage} to true.
  48. * Then, the session data will be stored and retrieved using the above methods.
  49. *
  50. * CHttpSession is a Web application component that can be accessed via
  51. * {@link CWebApplication::getSession()}.
  52. *
  53. * @property boolean $useCustomStorage Whether to use custom storage.
  54. * @property boolean $isStarted Whether the session has started.
  55. * @property string $sessionID The current session ID.
  56. * @property string $sessionName The current session name.
  57. * @property string $savePath The current session save path, defaults to {@link http://php.net/session.save_path}.
  58. * @property array $cookieParams The session cookie parameters.
  59. * @property string $cookieMode How to use cookie to store session ID. Defaults to 'Allow'.
  60. * @property float $gCProbability The probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
  61. * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to false.
  62. * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.
  63. * @property CHttpSessionIterator $iterator An iterator for traversing the session variables.
  64. * @property integer $count The number of session variables.
  65. * @property array $keys The list of session variable names.
  66. *
  67. * @author Qiang Xue <qiang.xue@gmail.com>
  68. * @package system.web
  69. * @since 1.0
  70. */
  71. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  72. {
  73. /**
  74. * @var boolean whether the session should be automatically started when the session application component is initialized, defaults to true.
  75. */
  76. public $autoStart=true;
  77. /**
  78. * Initializes the application component.
  79. * This method is required by IApplicationComponent and is invoked by application.
  80. */
  81. public function init()
  82. {
  83. parent::init();
  84. if($this->autoStart)
  85. $this->open();
  86. register_shutdown_function(array($this,'close'));
  87. }
  88. /**
  89. * Returns a value indicating whether to use custom session storage.
  90. * This method should be overriden to return true if custom session storage handler should be used.
  91. * If returning true, make sure the methods {@link openSession}, {@link closeSession}, {@link readSession},
  92. * {@link writeSession}, {@link destroySession}, and {@link gcSession} are overridden in child
  93. * class, because they will be used as the callback handlers.
  94. * The default implementation always return false.
  95. * @return boolean whether to use custom storage.
  96. */
  97. public function getUseCustomStorage()
  98. {
  99. return false;
  100. }
  101. /**
  102. * Starts the session if it has not started yet.
  103. */
  104. public function open()
  105. {
  106. if($this->getUseCustomStorage())
  107. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  108. @session_start();
  109. if(YII_DEBUG && session_id()=='')
  110. {
  111. $message=Yii::t('yii','Failed to start session.');
  112. if(function_exists('error_get_last'))
  113. {
  114. $error=error_get_last();
  115. if(isset($error['message']))
  116. $message=$error['message'];
  117. }
  118. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  119. }
  120. }
  121. /**
  122. * Ends the current session and store session data.
  123. */
  124. public function close()
  125. {
  126. if(session_id()!=='')
  127. @session_write_close();
  128. }
  129. /**
  130. * Frees all session variables and destroys all data registered to a session.
  131. */
  132. public function destroy()
  133. {
  134. if(session_id()!=='')
  135. {
  136. @session_unset();
  137. @session_destroy();
  138. }
  139. }
  140. /**
  141. * @return boolean whether the session has started
  142. */
  143. public function getIsStarted()
  144. {
  145. return session_id()!=='';
  146. }
  147. /**
  148. * @return string the current session ID
  149. */
  150. public function getSessionID()
  151. {
  152. return session_id();
  153. }
  154. /**
  155. * @param string $value the session ID for the current session
  156. */
  157. public function setSessionID($value)
  158. {
  159. session_id($value);
  160. }
  161. /**
  162. * Updates the current session id with a newly generated one .
  163. * Please refer to {@link http://php.net/session_regenerate_id} for more details.
  164. * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
  165. * @since 1.1.8
  166. */
  167. public function regenerateID($deleteOldSession=false)
  168. {
  169. if($this->getIsStarted())
  170. session_regenerate_id($deleteOldSession);
  171. }
  172. /**
  173. * @return string the current session name
  174. */
  175. public function getSessionName()
  176. {
  177. return session_name();
  178. }
  179. /**
  180. * @param string $value the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID
  181. */
  182. public function setSessionName($value)
  183. {
  184. session_name($value);
  185. }
  186. /**
  187. * @return string the current session save path, defaults to {@link http://php.net/session.save_path}.
  188. */
  189. public function getSavePath()
  190. {
  191. return session_save_path();
  192. }
  193. /**
  194. * @param string $value the current session save path
  195. * @throws CException if the path is not a valid directory
  196. */
  197. public function setSavePath($value)
  198. {
  199. if(is_dir($value))
  200. session_save_path($value);
  201. else
  202. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  203. array('{path}'=>$value)));
  204. }
  205. /**
  206. * @return array the session cookie parameters.
  207. * @see http://us2.php.net/manual/en/function.session-get-cookie-params.php
  208. */
  209. public function getCookieParams()
  210. {
  211. return session_get_cookie_params();
  212. }
  213. /**
  214. * Sets the session cookie parameters.
  215. * The effect of this method only lasts for the duration of the script.
  216. * Call this method before the session starts.
  217. * @param array $value cookie parameters, valid keys include: lifetime, path,
  218. * domain, secure, httponly. Note that httponly is all lowercase.
  219. * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
  220. */
  221. public function setCookieParams($value)
  222. {
  223. $data=session_get_cookie_params();
  224. extract($data);
  225. extract($value);
  226. if(isset($httponly))
  227. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  228. else
  229. session_set_cookie_params($lifetime,$path,$domain,$secure);
  230. }
  231. /**
  232. * @return string how to use cookie to store session ID. Defaults to 'Allow'.
  233. */
  234. public function getCookieMode()
  235. {
  236. if(ini_get('session.use_cookies')==='0')
  237. return 'none';
  238. elseif(ini_get('session.use_only_cookies')==='0')
  239. return 'allow';
  240. else
  241. return 'only';
  242. }
  243. /**
  244. * @param string $value how to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'.
  245. */
  246. public function setCookieMode($value)
  247. {
  248. if($value==='none')
  249. {
  250. ini_set('session.use_cookies','0');
  251. ini_set('session.use_only_cookies','0');
  252. }
  253. elseif($value==='allow')
  254. {
  255. ini_set('session.use_cookies','1');
  256. ini_set('session.use_only_cookies','0');
  257. }
  258. elseif($value==='only')
  259. {
  260. ini_set('session.use_cookies','1');
  261. ini_set('session.use_only_cookies','1');
  262. }
  263. else
  264. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  265. }
  266. /**
  267. * @return float the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
  268. */
  269. public function getGCProbability()
  270. {
  271. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  272. }
  273. /**
  274. * @param float $value the probability (percentage) that the gc (garbage collection) process is started on every session initialization.
  275. * @throws CException if the value is beyond [0,100]
  276. */
  277. public function setGCProbability($value)
  278. {
  279. if($value>=0 && $value<=100)
  280. {
  281. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  282. ini_set('session.gc_probability',floor($value*21474836.47));
  283. ini_set('session.gc_divisor',2147483647);
  284. }
  285. else
  286. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  287. array('{value}'=>$value)));
  288. }
  289. /**
  290. * @return boolean whether transparent sid support is enabled or not, defaults to false.
  291. */
  292. public function getUseTransparentSessionID()
  293. {
  294. return ini_get('session.use_trans_sid')==1;
  295. }
  296. /**
  297. * @param boolean $value whether transparent sid support is enabled or not.
  298. */
  299. public function setUseTransparentSessionID($value)
  300. {
  301. ini_set('session.use_trans_sid',$value?'1':'0');
  302. }
  303. /**
  304. * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.
  305. */
  306. public function getTimeout()
  307. {
  308. return (int)ini_get('session.gc_maxlifetime');
  309. }
  310. /**
  311. * @param integer $value the number of seconds after which data will be seen as 'garbage' and cleaned up
  312. */
  313. public function setTimeout($value)
  314. {
  315. ini_set('session.gc_maxlifetime',$value);
  316. }
  317. /**
  318. * Session open handler.
  319. * This method should be overridden if {@link useCustomStorage} is set true.
  320. * Do not call this method directly.
  321. * @param string $savePath session save path
  322. * @param string $sessionName session name
  323. * @return boolean whether session is opened successfully
  324. */
  325. public function openSession($savePath,$sessionName)
  326. {
  327. return true;
  328. }
  329. /**
  330. * Session close handler.
  331. * This method should be overridden if {@link useCustomStorage} is set true.
  332. * Do not call this method directly.
  333. * @return boolean whether session is closed successfully
  334. */
  335. public function closeSession()
  336. {
  337. return true;
  338. }
  339. /**
  340. * Session read handler.
  341. * This method should be overridden if {@link useCustomStorage} is set true.
  342. * Do not call this method directly.
  343. * @param string $id session ID
  344. * @return string the session data
  345. */
  346. public function readSession($id)
  347. {
  348. return '';
  349. }
  350. /**
  351. * Session write handler.
  352. * This method should be overridden if {@link useCustomStorage} is set true.
  353. * Do not call this method directly.
  354. * @param string $id session ID
  355. * @param string $data session data
  356. * @return boolean whether session write is successful
  357. */
  358. public function writeSession($id,$data)
  359. {
  360. return true;
  361. }
  362. /**
  363. * Session destroy handler.
  364. * This method should be overridden if {@link useCustomStorage} is set true.
  365. * Do not call this method directly.
  366. * @param string $id session ID
  367. * @return boolean whether session is destroyed successfully
  368. */
  369. public function destroySession($id)
  370. {
  371. return true;
  372. }
  373. /**
  374. * Session GC (garbage collection) handler.
  375. * This method should be overridden if {@link useCustomStorage} is set true.
  376. * Do not call this method directly.
  377. * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  378. * @return boolean whether session is GCed successfully
  379. */
  380. public function gcSession($maxLifetime)
  381. {
  382. return true;
  383. }
  384. //------ The following methods enable CHttpSession to be CMap-like -----
  385. /**
  386. * Returns an iterator for traversing the session variables.
  387. * This method is required by the interface IteratorAggregate.
  388. * @return CHttpSessionIterator an iterator for traversing the session variables.
  389. */
  390. public function getIterator()
  391. {
  392. return new CHttpSessionIterator;
  393. }
  394. /**
  395. * Returns the number of items in the session.
  396. * @return integer the number of session variables
  397. */
  398. public function getCount()
  399. {
  400. return count($_SESSION);
  401. }
  402. /**
  403. * Returns the number of items in the session.
  404. * This method is required by Countable interface.
  405. * @return integer number of items in the session.
  406. */
  407. public function count()
  408. {
  409. return $this->getCount();
  410. }
  411. /**
  412. * @return array the list of session variable names
  413. */
  414. public function getKeys()
  415. {
  416. return array_keys($_SESSION);
  417. }
  418. /**
  419. * Returns the session variable value with the session variable name.
  420. * This method is very similar to {@link itemAt} and {@link offsetGet},
  421. * except that it will return $defaultValue if the session variable does not exist.
  422. * @param mixed $key the session variable name
  423. * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
  424. * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
  425. * @since 1.1.2
  426. */
  427. public function get($key,$defaultValue=null)
  428. {
  429. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  430. }
  431. /**
  432. * Returns the session variable value with the session variable name.
  433. * This method is exactly the same as {@link offsetGet}.
  434. * @param mixed $key the session variable name
  435. * @return mixed the session variable value, null if no such variable exists
  436. */
  437. public function itemAt($key)
  438. {
  439. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  440. }
  441. /**
  442. * Adds a session variable.
  443. * Note, if the specified name already exists, the old value will be removed first.
  444. * @param mixed $key session variable name
  445. * @param mixed $value session variable value
  446. */
  447. public function add($key,$value)
  448. {
  449. $_SESSION[$key]=$value;
  450. }
  451. /**
  452. * Removes a session variable.
  453. * @param mixed $key the name of the session variable to be removed
  454. * @return mixed the removed value, null if no such session variable.
  455. */
  456. public function remove($key)
  457. {
  458. if(isset($_SESSION[$key]))
  459. {
  460. $value=$_SESSION[$key];
  461. unset($_SESSION[$key]);
  462. return $value;
  463. }
  464. else
  465. return null;
  466. }
  467. /**
  468. * Removes all session variables
  469. */
  470. public function clear()
  471. {
  472. foreach(array_keys($_SESSION) as $key)
  473. unset($_SESSION[$key]);
  474. }
  475. /**
  476. * @param mixed $key session variable name
  477. * @return boolean whether there is the named session variable
  478. */
  479. public function contains($key)
  480. {
  481. return isset($_SESSION[$key]);
  482. }
  483. /**
  484. * @return array the list of all session variables in array
  485. */
  486. public function toArray()
  487. {
  488. return $_SESSION;
  489. }
  490. /**
  491. * This method is required by the interface ArrayAccess.
  492. * @param mixed $offset the offset to check on
  493. * @return boolean
  494. */
  495. public function offsetExists($offset)
  496. {
  497. return isset($_SESSION[$offset]);
  498. }
  499. /**
  500. * This method is required by the interface ArrayAccess.
  501. * @param integer $offset the offset to retrieve element.
  502. * @return mixed the element at the offset, null if no element is found at the offset
  503. */
  504. public function offsetGet($offset)
  505. {
  506. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  507. }
  508. /**
  509. * This method is required by the interface ArrayAccess.
  510. * @param integer $offset the offset to set element
  511. * @param mixed $item the element value
  512. */
  513. public function offsetSet($offset,$item)
  514. {
  515. $_SESSION[$offset]=$item;
  516. }
  517. /**
  518. * This method is required by the interface ArrayAccess.
  519. * @param mixed $offset the offset to unset element
  520. */
  521. public function offsetUnset($offset)
  522. {
  523. unset($_SESSION[$offset]);
  524. }
  525. }