Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: helper cookie not working #3939

Closed
dz-id opened this issue Nov 28, 2020 · 1 comment
Closed

Bug: helper cookie not working #3939

dz-id opened this issue Nov 28, 2020 · 1 comment
Labels
bug Verified issues on the current code behavior or pull requests that will fix them

Comments

@dz-id
Copy link

dz-id commented Nov 28, 2020

cookie helper not working,

helper("cookie");
$app = config("App");

set_cookie(
 "token",
 "test",
 time() + 3600,
 $app->cookieDomain, // "localhost:8080"
 $app->cookiePath, // "/"
 $app->cookiePrefix, // ""
 $app->cookieHTTPOnly, // false
 true
);

dd(get_cookie("token")); // null

I tried to refresh the browser, but the result was the same // null

@dz-id dz-id added the bug Verified issues on the current code behavior or pull requests that will fix them label Nov 28, 2020
@paulbalandan
Copy link
Member

paulbalandan commented Jan 11, 2021

This is a common pitfall with cookies. Quoting PHP.net:

Cookies will not become visible until the next loading of a page that the cookie should be visible for.

CI4's set_cookie sets a new cookie in the Response object but it sits there until the headers are sent. get_cookie uses the Request object to retrieve the cookie in the $_COOKIE array. In your example, since you are setting and getting the same cookie on the same page, then cookies are not sent to the browser and therefore the $_COOKIE is not populated with the cookies in the Response. That's why you are getting null (i.e., cookie not in $_COOKIE).

To achieve your desired result, create two pages: (1) setting the cookie; (2) getting the cookie. In your cookie-setting page, you will redirect with cookies to the cookie-getting page, something like redirect('/my-cookie-getter')->withCookies();. Then, there the dd should show the cookies.

Side note: The arguments order supplied in set_cookie in your example is wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Verified issues on the current code behavior or pull requests that will fix them
Projects
None yet
Development

No branches or pull requests

2 participants