CHttpSession.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. session_regenerate_id($deleteOldSession);
  170. }
  171. /**
  172. * @return string the current session name
  173. */
  174. public function getSessionName()
  175. {
  176. return session_name();
  177. }
  178. /**
  179. * @param string $value the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID
  180. */
  181. public function setSessionName($value)
  182. {
  183. session_name($value);
  184. }
  185. /**
  186. * @return string the current session save path, defaults to {@link http://php.net/session.save_path}.
  187. */
  188. public function getSavePath()
  189. {
  190. return session_save_path();
  191. }
  192. /**
  193. * @param string $value the current session save path
  194. * @throws CException if the path is not a valid directory
  195. */
  196. public function setSavePath($value)
  197. {
  198. if(is_dir($value))
  199. session_save_path($value);
  200. else
  201. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  202. array('{path}'=>$value)));
  203. }
  204. /**
  205. * @return array the session cookie parameters.
  206. * @see http://us2.php.net/manual/en/function.session-get-cookie-params.php
  207. */
  208. public function getCookieParams()
  209. {
  210. return session_get_cookie_params();
  211. }
  212. /**
  213. * Sets the session cookie parameters.
  214. * The effect of this method only lasts for the duration of the script.
  215. * Call this method before the session starts.
  216. * @param array $value cookie parameters, valid keys include: lifetime, path,
  217. * domain, secure, httponly. Note that httponly is all lowercase.
  218. * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
  219. */
  220. public function setCookieParams($value)
  221. {
  222. $data=session_get_cookie_params();
  223. extract($data);
  224. extract($value);
  225. if(isset($httponly))
  226. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  227. else
  228. session_set_cookie_params($lifetime,$path,$domain,$secure);
  229. }
  230. /**
  231. * @return string how to use cookie to store session ID. Defaults to 'Allow'.
  232. */
  233. public function getCookieMode()
  234. {
  235. if(ini_get('session.use_cookies')==='0')
  236. return 'none';
  237. elseif(ini_get('session.use_only_cookies')==='0')
  238. return 'allow';
  239. else
  240. return 'only';
  241. }
  242. /**
  243. * @param string $value how to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'.
  244. */
  245. public function setCookieMode($value)
  246. {
  247. if($value==='none')
  248. {
  249. ini_set('session.use_cookies','0');
  250. ini_set('session.use_only_cookies','0');
  251. }
  252. elseif($value==='allow')
  253. {
  254. ini_set('session.use_cookies','1');
  255. ini_set('session.use_only_cookies','0');
  256. }
  257. elseif($value==='only')
  258. {
  259. ini_set('session.use_cookies','1');
  260. ini_set('session.use_only_cookies','1');
  261. }
  262. else
  263. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  264. }
  265. /**
  266. * @return float the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
  267. */
  268. public function getGCProbability()
  269. {
  270. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  271. }
  272. /**
  273. * @param float $value the probability (percentage) that the gc (garbage collection) process is started on every session initialization.
  274. * @throws CException if the value is beyond [0,100]
  275. */
  276. public function setGCProbability($value)
  277. {
  278. if($value>=0 && $value<=100)
  279. {
  280. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  281. ini_set('session.gc_probability',floor($value*21474836.47));
  282. ini_set('session.gc_divisor',2147483647);
  283. }
  284. else
  285. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  286. array('{value}'=>$value)));
  287. }
  288. /**
  289. * @return boolean whether transparent sid support is enabled or not, defaults to false.
  290. */
  291. public function getUseTransparentSessionID()
  292. {
  293. return ini_get('session.use_trans_sid')==1;
  294. }
  295. /**
  296. * @param boolean $value whether transparent sid support is enabled or not.
  297. */
  298. public function setUseTransparentSessionID($value)
  299. {
  300. ini_set('session.use_trans_sid',$value?'1':'0');
  301. }
  302. /**
  303. * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.
  304. */
  305. public function getTimeout()
  306. {
  307. return (int)ini_get('session.gc_maxlifetime');
  308. }
  309. /**
  310. * @param integer $value the number of seconds after which data will be seen as 'garbage' and cleaned up
  311. */
  312. public function setTimeout($value)
  313. {
  314. ini_set('session.gc_maxlifetime',$value);
  315. }
  316. /**
  317. * Session open handler.
  318. * This method should be overridden if {@link useCustomStorage} is set true.
  319. * Do not call this method directly.
  320. * @param string $savePath session save path
  321. * @param string $sessionName session name
  322. * @return boolean whether session is opened successfully
  323. */
  324. public function openSession($savePath,$sessionName)
  325. {
  326. return true;
  327. }
  328. /**
  329. * Session close handler.
  330. * This method should be overridden if {@link useCustomStorage} is set true.
  331. * Do not call this method directly.
  332. * @return boolean whether session is closed successfully
  333. */
  334. public function closeSession()
  335. {
  336. return true;
  337. }
  338. /**
  339. * Session read handler.
  340. * This method should be overridden if {@link useCustomStorage} is set true.
  341. * Do not call this method directly.
  342. * @param string $id session ID
  343. * @return string the session data
  344. */
  345. public function readSession($id)
  346. {
  347. return '';
  348. }
  349. /**
  350. * Session write handler.
  351. * This method should be overridden if {@link useCustomStorage} is set true.
  352. * Do not call this method directly.
  353. * @param string $id session ID
  354. * @param string $data session data
  355. * @return boolean whether session write is successful
  356. */
  357. public function writeSession($id,$data)
  358. {
  359. return true;
  360. }
  361. /**
  362. * Session destroy handler.
  363. * This method should be overridden if {@link useCustomStorage} is set true.
  364. * Do not call this method directly.
  365. * @param string $id session ID
  366. * @return boolean whether session is destroyed successfully
  367. */
  368. public function destroySession($id)
  369. {
  370. return true;
  371. }
  372. /**
  373. * Session GC (garbage collection) handler.
  374. * This method should be overridden if {@link useCustomStorage} is set true.
  375. * Do not call this method directly.
  376. * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  377. * @return boolean whether session is GCed successfully
  378. */
  379. public function gcSession($maxLifetime)
  380. {
  381. return true;
  382. }
  383. //------ The following methods enable CHttpSession to be CMap-like -----
  384. /**
  385. * Returns an iterator for traversing the session variables.
  386. * This method is required by the interface IteratorAggregate.
  387. * @return CHttpSessionIterator an iterator for traversing the session variables.
  388. */
  389. public function getIterator()
  390. {
  391. return new CHttpSessionIterator;
  392. }
  393. /**
  394. * Returns the number of items in the session.
  395. * @return integer the number of session variables
  396. */
  397. public function getCount()
  398. {
  399. return count($_SESSION);
  400. }
  401. /**
  402. * Returns the number of items in the session.
  403. * This method is required by Countable interface.
  404. * @return integer number of items in the session.
  405. */
  406. public function count()
  407. {
  408. return $this->getCount();
  409. }
  410. /**
  411. * @return array the list of session variable names
  412. */
  413. public function getKeys()
  414. {
  415. return array_keys($_SESSION);
  416. }
  417. /**
  418. * Returns the session variable value with the session variable name.
  419. * This method is very similar to {@link itemAt} and {@link offsetGet},
  420. * except that it will return $defaultValue if the session variable does not exist.
  421. * @param mixed $key the session variable name
  422. * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
  423. * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
  424. * @since 1.1.2
  425. */
  426. public function get($key,$defaultValue=null)
  427. {
  428. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  429. }
  430. /**
  431. * Returns the session variable value with the session variable name.
  432. * This method is exactly the same as {@link offsetGet}.
  433. * @param mixed $key the session variable name
  434. * @return mixed the session variable value, null if no such variable exists
  435. */
  436. public function itemAt($key)
  437. {
  438. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  439. }
  440. /**
  441. * Adds a session variable.
  442. * Note, if the specified name already exists, the old value will be removed first.
  443. * @param mixed $key session variable name
  444. * @param mixed $value session variable value
  445. */
  446. public function add($key,$value)
  447. {
  448. $_SESSION[$key]=$value;
  449. }
  450. /**
  451. * Removes a session variable.
  452. * @param mixed $key the name of the session variable to be removed
  453. * @return mixed the removed value, null if no such session variable.
  454. */
  455. public function remove($key)
  456. {
  457. if(isset($_SESSION[$key]))
  458. {
  459. $value=$_SESSION[$key];
  460. unset($_SESSION[$key]);
  461. return $value;
  462. }
  463. else
  464. return null;
  465. }
  466. /**
  467. * Removes all session variables
  468. */
  469. public function clear()
  470. {
  471. foreach(array_keys($_SESSION) as $key)
  472. unset($_SESSION[$key]);
  473. }
  474. /**
  475. * @param mixed $key session variable name
  476. * @return boolean whether there is the named session variable
  477. */
  478. public function contains($key)
  479. {
  480. return isset($_SESSION[$key]);
  481. }
  482. /**
  483. * @return array the list of all session variables in array
  484. */
  485. public function toArray()
  486. {
  487. return $_SESSION;
  488. }
  489. /**
  490. * This method is required by the interface ArrayAccess.
  491. * @param mixed $offset the offset to check on
  492. * @return boolean
  493. */
  494. public function offsetExists($offset)
  495. {
  496. return isset($_SESSION[$offset]);
  497. }
  498. /**
  499. * This method is required by the interface ArrayAccess.
  500. * @param integer $offset the offset to retrieve element.
  501. * @return mixed the element at the offset, null if no element is found at the offset
  502. */
  503. public function offsetGet($offset)
  504. {
  505. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  506. }
  507. /**
  508. * This method is required by the interface ArrayAccess.
  509. * @param integer $offset the offset to set element
  510. * @param mixed $item the element value
  511. */
  512. public function offsetSet($offset,$item)
  513. {
  514. $_SESSION[$offset]=$item;
  515. }
  516. /**
  517. * This method is required by the interface ArrayAccess.
  518. * @param mixed $offset the offset to unset element
  519. */
  520. public function offsetUnset($offset)
  521. {
  522. unset($_SESSION[$offset]);
  523. }
  524. }