Search code examples
phpcodeignitercodeigniter-4

Unable to set login remember me cookies when redirect initialized ci4


I want to add remember me option to my login functionality, When I set remember me option without redirecting user to his access success page, the cookie stored perfect, but the issue is when I uncomment the redirection. When user attempt to login it redirect and bypass the process to store cookies. How can I fix this issue?

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');               
        }
    }
}

Solution

  • You must set cookie path to / to work for all paths, not just current one.

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

    As I read on this post How can I set a cookie and then redirect in PHP?