Why doesn't php's $_COOKIE read cookies synchronously?
Get the solution ↓↓↓In my php app (no specific framework) I have a page with one required file where I am storing a cookie (using js cookie ) depending on the url - as in
child.php
<?
// some PHP code
?>
<!-- some HTML/JS code -->
<script>
Cookies.set('c', window.location.pathname);
$('.el').on('click', {
window.location = "/parent.php?path=pathname" // this reloads the parent so it can reload the parent and process the previously stored cookie as well as handling other features are displayed based on `path GET parameter`
});
</script>
?>
Then I want to show (use) the cookie in the newly loaded page (and parent of child.php) in PHP code as in
parent.php
require_once("child.php"); // including the file here is supposed to process the cookie store logic, which indeed (on the frontend side) does
if($_COOKIE['c'] = 'xyz') { //etc. }
but $_COOKIE['c'] is empty when printing it toerror_log
(as if the newly stored cookie wasn't there), whereas after reloading the cookie is displayed correctly (hence why I am assuming it is correctly fetching the cookie but that cookie is available asynchronously)
Why?
UPDATE: headers (Cookies) the browser sends when opening the page the first time right after you click that element (and page reloads)
no cookie "c"
when re-opening the page from the link
c:xyz
the same applies if clicking the link twice (which itself triggerslocation.reload
)
The headercache-control
is set tono-cache
So what I see happening is that $_COOKIE['c'] returns an empty string because on first load that http cookie is not available, but how can I have it available without having to reload twice?
Answer
Solution:
When the page is served for the first time - the cookie IS NOT SET YET.
The steps are the following:
- The page fully renders (cookie was not set yet)
- Browser evaluates the page, including JS, that sets the cookie
- You refresh the page, now the cookie is set - hence a browser sends it in the request and php on the server side sees it.
So the problem is that step 1 happens much earlier than the step 2, it has nothing to do with synchronicity.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function update() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.