Codeigniter 4 cookies issue not able to set

Viewed 3368

This is my controller code. I am not able to set and get the cookies in Codeigniter 4.

helper('cookie');
$this->response->set_cookie('forgetpwd',$token, time() + (3600),"/",site_url());
print_r($this->request->get_cookie('forgetpwd'));
die();
2 Answers

Do not use die() because then the cookie will not be set. Let the method return instead so CI can output cookies and headers.

You do not need the helper, don't load it.

site_url() does not produce the string you should be using. It includes the protocol, i.e. https://example.com when all you should use is 'example.com'.

You have the domain and path arguments reversed and as others have said the call is to setCookie() as in

$this->response->setCookie('forgetpwd', $token, 3600, example.com);

The expire argument can be the life (in seconds) you want. The setCookie() method will add time() to it for you.

I don't supply a path argument because you need the default value of '/'.

From php.net - https://www.php.net/manual/en/function.setcookie.php

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expires parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Related