指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

今天在弄cookie的时候,需要设置过期时间,如下是我的代码:

public function onAuthenticationSuccess(Request $request, TokenInterface $token): RedirectResponse|Response
    {
        /** @var User $user */
        $user = $token->getUser();
        $userInfo = [];
        if ($user) {
            $userInfo['id'] = $user->getId();
            $userInfo['email'] = $user->getEmail();
            $userInfo['firstName'] = $user->getFirstName();
            $userInfo['middleName'] = $user->getMiddleName();
            $userInfo['lastName'] = $user->getLastName();
            $userInfo['isAdmin'] = count($user->getRoles()) > 1 ? 1 : 0;
            $userInfo['image'] = $user->getImage();
            $userInfo['avatar'] = $user->getAvatar();
        }

        //设置过期时间,symfony5.4 框架会把下面这个时间戳格式化为UTC格式,北京时间少八个小时
        //开始我为了测试用 time() + 60; 然后盯着(期间也不停地刷新浏览器)浏览器等待60s,却发现最然设置了过期时间,但是
        //cookie数据还在,后来我想是不是 UTC的缘故,又把时间设置为:time() + 8 * 3600 + 60,
        //多加8小时,也不行,其实 虽然加了8小时,但是cookie过期的时间格式依然是:2023-05-09T00:46:49.518Z (UTC)
        //所以,time() + 60; 这样就可以了,然后关闭浏览器,再打开,再看,大约60s,以后 数据自动清除
        //总结就是:这个过期时间会在关闭浏览器再打开才会体现出来.
        $expireTime = time() + 3600;
        $response = $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));
        $cookie = new Cookie('userInfo', json_encode($userInfo), $expireTime, '/', null, null, false);
        $response->headers->setCookie($cookie);

        return $response;
    }