Search code examples
codeignitercodeigniter-4

How to work with cookie and redirect in codeigniter4


Hellow everyone. I'm working with codeigniter4 where I want to be able to store cookie and then redirect to another page. If I set a cookie without including redirection process, Cookie stores successfully, But the issue is when I do redirection, the cookie did't saved anymore. How can I solve and make cookie saved and redirect.

public function loginProcessor()
{
    helper(['cookie']);
    $checkStatus = true;

    if ($checkStatus) 
    {
        set_cookie('nameCookie', 'CookieSomething', time() + 60*60*24*30);
    }

    return redirect()->to('dashboard');
}

Solution

  • It's worth saying I've also had problems with the Session library which uses the Cookie functions so have resorted to an older version which did work.

    function setMyCookie($name,$value,$time,$params = array()){
        if (empty($params)){
            $config = config('App');
    
            $params = array(
                'expires'   => $time,
                'path'      => $config->cookiePath,
                'domain'    => $config->cookieDomain,
                'secure'    => $config->cookieSecure,
                'httponly'  => $config->cookieHTTPOnly,
                'samesite'  => $config->cookieSameSite,
            );
        }
    
        setcookie($name,$value,$params);
    }
    

    This is saved as a helper and then called from the controllers etc.