首页 > 解决方案 > 重定向初始化 ci4 时无法设置登录记住我的 cookie

问题描述

我想在我的登录功能中添加记住我选项,当我设置记住我选项而不将用户重定向到他的访问成功页面时,cookie 存储完美,但问题是当我取消注释重定向时。当用户尝试登录时,它会重定向并绕过存储 cookie 的过程。我该如何解决这个问题?

public function login(){
    $username = $this->request->getPost('username');
    $password = $this->request->getPost('password');

    $user = $this->model->getLoginData($username); 
    $rowCount = count([$user]);

    if($user){
        if (password_verify($password, $user->password)){
            //store session data
            $this->auth->userSession($user);

            //remember me 
            if(!empty($this->request->getPost("remember"))){
                $cookie_hash = md5(uniqid()."sghsgd876mbjb");
                set_cookie('hash_cookie', $cookie_hash, 36000 );
            }else{
                set_cookie('hash_cookie', '');
            }  

            return redirect()->to('/manager');               
        }
    }
}

标签: phpcodeignitercodeigniter-4

解决方案


您必须将 cookie 路径设置为 / 以适用于所有路径,而不仅仅是当前路径。

set_cookie('hash_cookie', $cookie_hash, 36000, '/' );

正如我在这篇文章中所读到的, 如何设置 cookie,然后在 PHP 中重定向?


推荐阅读