CodeIgniter Forums
CI4 Helper Function set_cookie doesn't create a cookie on browser - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Development (https://forum.codeigniter.com/forum-6.html)
+--- Forum: Issues (https://forum.codeigniter.com/forum-19.html)
+--- Thread: CI4 Helper Function set_cookie doesn't create a cookie on browser (/thread-79362.html)



CI4 Helper Function set_cookie doesn't create a cookie on browser - vtankaria - 06-04-2021

CI4 Helper Function set_cookie doesn't create a cookie on browser

Hello Everyone,

I am working on Codeigniter  v4.1.2. I created a login page, and was trying to create a cookie using a Helper function set_cookie
.

Code:
set_cookie("cookie_name","cookie_value","cookie_expiry")

Inside Cookie Helper Code PROJECT_PATH/vendor/codeigniter4/framework/system/Helpers/cookie_helper.php

The set_cookie function calls the Service Response
Code:
setCookie 
Method.

In the Service Response setCookie Method, it calls the put method in PROJECT_PATH/vendor/codeigniter4/framework/system/Cookie/CookieStore.php

Code:
$this->cookieStore = $this->cookieStore->put($cookie);


Code:
public function put(Cookie $cookie)
{
    $store = clone $this;

    $store->cookies[$cookie->getId()] = $cookie;

    return $store;
}


The put method, just creates a clone of the class and assigns the sets the new cookie.
However, it doesn't create any cookie on browser and returns the class object.

I added the Line
Code:
$store->dispatch();
to create the cookie after its sent in the variable.
Code to Create a cookie on browser is written in dispatch() function.

Code:
public function put(Cookie $cookie)
{
$store = clone $this;

$store->cookies[$cookie->getId()] = $cookie;

$store->dispatch();// added by me, so a cookie is created on browser

return $store;
}


I think many people would be facing this issue. As I found similar issue posted on Stackoverflow https://stackoverflow.com/questions/66778869/codeigniter-4-set-cookie-not-setting , 2 months back.

Can someone help with this?

Thank you.


RE: CI4 Helper Function set_cookie doesn't create a cookie on browser - includebeer - 06-09-2021

Show your code. How do you set and read the cookie? 
Is it all on the same page?
Do you have the same problem as this? https://github.com/codeigniter4/CodeIgniter4/issues/3939


RE: CI4 Helper Function set_cookie doesn't create a cookie on browser - paliz - 06-09-2021

Frirst call helper cookie
Helper('cookie' ) :
Then setcookies ()