Session.php 9.4 KB

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