SessionInit.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace app\common\middleware;
  13. use Closure;
  14. use think\App;
  15. use think\Request;
  16. use think\Response;
  17. use think\Session;
  18. /**
  19. * Session初始化
  20. */
  21. class SessionInit
  22. {
  23. public function __construct(protected App $app, protected Session $session)
  24. {
  25. }
  26. /**
  27. * Session初始化
  28. * @access public
  29. * @param Request $request
  30. * @param Closure $next
  31. * @return Response
  32. */
  33. public function handle(Request $request, Closure $next): Response
  34. {
  35. // Session初始化
  36. $varSessionId = $this->app->config->get('session.var_session_id');
  37. $cookieName = $this->session->getName();
  38. $http_sid = $request->server("HTTP_SID");
  39. if ($varSessionId && $request->request($varSessionId)) {
  40. $sessionId = $request->request($varSessionId);
  41. } elseif ($http_sid) {
  42. $sessionId = $http_sid;
  43. } else {
  44. $sessionId = $request->cookie($cookieName);
  45. }
  46. if ($sessionId) {
  47. $this->session->setId($sessionId);
  48. }
  49. $this->session->init();
  50. $request->withSession($this->session);
  51. /** @var Response $response */
  52. $response = $next($request);
  53. $response->setSession($this->session);
  54. $this->app->cookie->set($cookieName, $this->session->getId(), $this->session->getConfig('expire'));
  55. return $response;
  56. }
  57. public function end(Response $response): void
  58. {
  59. $this->session->save();
  60. }
  61. }