0

I'm using Mo'Variables and Cookie Plus to read the current query string on a url. The cookie value doesn't update until a second page load occurs. I can see the cookie value is set correctly in the browser - but Cookie Plus just isn't outputting the current value. Here is the code I'm using:

{if query_string != ""} {exp:cookie_plus:set name="cookie" value="{query_string}" seconds="86400" parse="inward"} {/if}

and {exp:cookie_plus:get name="cookie"} to read the cookie.

Is there any workaround to instantly output the current cookie value? Using EE 2.8 currently.

1

The answer from witrin on this question (three answers down or so) is the reason why you you are having this problem.

https://stackoverflow.com/questions/3230133/accessing-cookie-immediately-after-setcookie

When you set the cookie via Cookie Plus, I assume it uses the setcookie() method. This sets a header to be sent to the client; when the client receives the cookie header, it creates the cookie. The cookie does not exist in your PHP execution cycle of first visit, just the header to be sent. On refresh, the cookie is sent back to your server as part of the response, and your execution can then see the cookie.

This is appropriate. A client can be configured to not create cookies; this would mean that even though your header was sent, a cookie was not created. As I said, when you set a cookie in PHP, you're essentially setting a request to be sent to the client to create the cookie.

If for some reason you need to retrieve the cookie in the same execution as you set it, the best you can do is the work around from witrin's answer (some of the other answers' work around might work for you as well). Note that with this method, the cookie is not guaranteed to be created by the client; but this won't be an issue: 99.999% of your real person traffic is just using a regular web browser that will create the cookie when the header is sent, so it's a safe bet it will be created.

If you have to retrieve the cookie immediately after it was created (on client first visit), you can also do so asynchronously via JavaScript.

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.