Session.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Protocols\Http;
  15. use Workerman\Protocols\Http\Session\FileSessionHandler;
  16. use Workerman\Protocols\Http\Session\SessionHandlerInterface;
  17. /**
  18. * Class Session
  19. * @package Workerman\Protocols\Http
  20. */
  21. class Session
  22. {
  23. /**
  24. * Session andler class which implements SessionHandlerInterface.
  25. *
  26. * @var string
  27. */
  28. protected static $_handlerClass = FileSessionHandler::class;
  29. /**
  30. * Parameters of __constructor for session handler class.
  31. *
  32. * @var null
  33. */
  34. protected static $_handlerConfig = null;
  35. /**
  36. * Session name.
  37. *
  38. * @var string
  39. */
  40. public static $name = 'PHPSID';
  41. /**
  42. * Auto update timestamp.
  43. *
  44. * @var bool
  45. */
  46. public static $autoUpdateTimestamp = false;
  47. /**
  48. * Session lifetime.
  49. *
  50. * @var int
  51. */
  52. public static $lifetime = 1440;
  53. /**
  54. * Cookie lifetime.
  55. *
  56. * @var int
  57. */
  58. public static $cookieLifetime = 1440;
  59. /**
  60. * Session cookie path.
  61. *
  62. * @var string
  63. */
  64. public static $cookiePath = '/';
  65. /**
  66. * Session cookie domain.
  67. *
  68. * @var string
  69. */
  70. public static $domain = '';
  71. /**
  72. * HTTPS only cookies.
  73. *
  74. * @var bool
  75. */
  76. public static $secure = false;
  77. /**
  78. * HTTP access only.
  79. *
  80. * @var bool
  81. */
  82. public static $httpOnly = true;
  83. /**
  84. * Same-site cookies.
  85. *
  86. * @var string
  87. */
  88. public static $sameSite = '';
  89. /**
  90. * Gc probability.
  91. *
  92. * @var int[]
  93. */
  94. public static $gcProbability = [1, 1000];
  95. /**
  96. * Session handler instance.
  97. *
  98. * @var SessionHandlerInterface
  99. */
  100. protected static $_handler = null;
  101. /**
  102. * Session data.
  103. *
  104. * @var array
  105. */
  106. protected $_data = [];
  107. /**
  108. * Session changed and need to save.
  109. *
  110. * @var bool
  111. */
  112. protected $_needSave = false;
  113. /**
  114. * Session id.
  115. *
  116. * @var null
  117. */
  118. protected $_sessionId = null;
  119. /**
  120. * Session constructor.
  121. *
  122. * @param string $session_id
  123. */
  124. public function __construct($session_id)
  125. {
  126. static::checkSessionId($session_id);
  127. if (static::$_handler === null) {
  128. static::initHandler();
  129. }
  130. $this->_sessionId = $session_id;
  131. if ($data = static::$_handler->read($session_id)) {
  132. $this->_data = \unserialize($data);
  133. }
  134. }
  135. /**
  136. * Get session id.
  137. *
  138. * @return string
  139. */
  140. public function getId()
  141. {
  142. return $this->_sessionId;
  143. }
  144. /**
  145. * Get session.
  146. *
  147. * @param string $name
  148. * @param mixed|null $default
  149. * @return mixed|null
  150. */
  151. public function get($name, $default = null)
  152. {
  153. return isset($this->_data[$name]) ? $this->_data[$name] : $default;
  154. }
  155. /**
  156. * Store data in the session.
  157. *
  158. * @param string $name
  159. * @param mixed $value
  160. */
  161. public function set($name, $value)
  162. {
  163. $this->_data[$name] = $value;
  164. $this->_needSave = true;
  165. }
  166. /**
  167. * Delete an item from the session.
  168. *
  169. * @param string $name
  170. */
  171. public function delete($name)
  172. {
  173. unset($this->_data[$name]);
  174. $this->_needSave = true;
  175. }
  176. /**
  177. * Retrieve and delete an item from the session.
  178. *
  179. * @param string $name
  180. * @param mixed|null $default
  181. * @return mixed|null
  182. */
  183. public function pull($name, $default = null)
  184. {
  185. $value = $this->get($name, $default);
  186. $this->delete($name);
  187. return $value;
  188. }
  189. /**
  190. * Store data in the session.
  191. *
  192. * @param string|array $key
  193. * @param mixed|null $value
  194. */
  195. public function put($key, $value = null)
  196. {
  197. if (!\is_array($key)) {
  198. $this->set($key, $value);
  199. return;
  200. }
  201. foreach ($key as $k => $v) {
  202. $this->_data[$k] = $v;
  203. }
  204. $this->_needSave = true;
  205. }
  206. /**
  207. * Remove a piece of data from the session.
  208. *
  209. * @param string $name
  210. */
  211. public function forget($name)
  212. {
  213. if (\is_scalar($name)) {
  214. $this->delete($name);
  215. return;
  216. }
  217. if (\is_array($name)) {
  218. foreach ($name as $key) {
  219. unset($this->_data[$key]);
  220. }
  221. }
  222. $this->_needSave = true;
  223. }
  224. /**
  225. * Retrieve all the data in the session.
  226. *
  227. * @return array
  228. */
  229. public function all()
  230. {
  231. return $this->_data;
  232. }
  233. /**
  234. * Remove all data from the session.
  235. *
  236. * @return void
  237. */
  238. public function flush()
  239. {
  240. $this->_needSave = true;
  241. $this->_data = [];
  242. }
  243. /**
  244. * Determining If An Item Exists In The Session.
  245. *
  246. * @param string $name
  247. * @return bool
  248. */
  249. public function has($name)
  250. {
  251. return isset($this->_data[$name]);
  252. }
  253. /**
  254. * To determine if an item is present in the session, even if its value is null.
  255. *
  256. * @param string $name
  257. * @return bool
  258. */
  259. public function exists($name)
  260. {
  261. return \array_key_exists($name, $this->_data);
  262. }
  263. /**
  264. * Save session to store.
  265. *
  266. * @return void
  267. */
  268. public function save()
  269. {
  270. if ($this->_needSave) {
  271. if (empty($this->_data)) {
  272. static::$_handler->destroy($this->_sessionId);
  273. } else {
  274. static::$_handler->write($this->_sessionId, \serialize($this->_data));
  275. }
  276. } elseif (static::$autoUpdateTimestamp) {
  277. static::refresh();
  278. }
  279. $this->_needSave = false;
  280. }
  281. /**
  282. * Refresh session expire time.
  283. *
  284. * @return bool
  285. */
  286. public function refresh()
  287. {
  288. static::$_handler->updateTimestamp($this->getId());
  289. }
  290. /**
  291. * Init.
  292. *
  293. * @return void
  294. */
  295. public static function init()
  296. {
  297. if ($gc_probability = (int)\ini_get('session.gc_probability') && $gc_divisor = (int)\ini_get('session.gc_divisor')) {
  298. static::$gcProbability = [$gc_probability, $gc_divisor];
  299. }
  300. if ($gc_max_life_time = \ini_get('session.gc_maxlifetime')) {
  301. self::$lifetime = (int)$gc_max_life_time;
  302. }
  303. $session_cookie_params = \session_get_cookie_params();
  304. static::$cookieLifetime = $session_cookie_params['lifetime'];
  305. static::$cookiePath = $session_cookie_params['path'];
  306. static::$domain = $session_cookie_params['domain'];
  307. static::$secure = $session_cookie_params['secure'];
  308. static::$httpOnly = $session_cookie_params['httponly'];
  309. }
  310. /**
  311. * Set session handler class.
  312. *
  313. * @param mixed|null $class_name
  314. * @param mixed|null $config
  315. * @return string
  316. */
  317. public static function handlerClass($class_name = null, $config = null)
  318. {
  319. if ($class_name) {
  320. static::$_handlerClass = $class_name;
  321. }
  322. if ($config) {
  323. static::$_handlerConfig = $config;
  324. }
  325. return static::$_handlerClass;
  326. }
  327. /**
  328. * Get cookie params.
  329. *
  330. * @return array
  331. */
  332. public static function getCookieParams()
  333. {
  334. return [
  335. 'lifetime' => static::$cookieLifetime,
  336. 'path' => static::$cookiePath,
  337. 'domain' => static::$domain,
  338. 'secure' => static::$secure,
  339. 'httponly' => static::$httpOnly,
  340. 'samesite' => static::$sameSite,
  341. ];
  342. }
  343. /**
  344. * Init handler.
  345. *
  346. * @return void
  347. */
  348. protected static function initHandler()
  349. {
  350. if (static::$_handlerConfig === null) {
  351. static::$_handler = new static::$_handlerClass();
  352. } else {
  353. static::$_handler = new static::$_handlerClass(static::$_handlerConfig);
  354. }
  355. }
  356. /**
  357. * GC sessions.
  358. *
  359. * @return void
  360. */
  361. public function gc()
  362. {
  363. static::$_handler->gc(static::$lifetime);
  364. }
  365. /**
  366. * __destruct.
  367. *
  368. * @return void
  369. */
  370. public function __destruct()
  371. {
  372. $this->save();
  373. if (\random_int(1, static::$gcProbability[1]) <= static::$gcProbability[0]) {
  374. $this->gc();
  375. }
  376. }
  377. /**
  378. * Check session id.
  379. *
  380. * @param string $session_id
  381. */
  382. protected static function checkSessionId($session_id)
  383. {
  384. if (!\preg_match('/^[a-zA-Z0-9]+$/', $session_id)) {
  385. throw new SessionException("session_id $session_id is invalid");
  386. }
  387. }
  388. }
  389. /**
  390. * Class SessionException
  391. * @package Workerman\Protocols\Http
  392. */
  393. class SessionException extends \RuntimeException
  394. {
  395. }
  396. // Init session.
  397. Session::init();