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();
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();
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);.
This code works for me. I get the cookie from the request and set it in the response. (Remember to validate the user input before processing it)
<?php
namespace App\Controllers;
use Config\Services;
class Home extends BaseController {
public function setLang($lang = ""){
// remember filter your inputs
Services::response()->setCookie('lang', $lang);
echo("<script>location='/index';</script>");
}
public function index(){
//default value
$lang = "es";
//if empty return NULL.
$tmpLang = Services::request()->getCookie("lang");
if(in_array($tmpLang, ["es", "en", "ja", "pt"])){
$lang = $tmpLang;
}
//show cookie value
echo $lang
}
}
?>
try using to redirect with cookies like
helper('cookie');
set_cookie('cookie_name', 'value', 14400);
return redirect()->to('url')->withCookies();
and on the page try getting by this way
print_r(get_cookie('cookie_name'));