简体   繁体   中英

Why doesn't php's $_COOKIE read cookies synchronously?

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 to error_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 triggers location.reload )

The header cache-control is set to no-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 ?

When the page is served for the first time - the cookie IS NOT SET YET .

The steps are the following:

  1. The page fully renders (cookie was not set yet)
  2. Browser evaluates the page, including JS, that sets the cookie
  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM