Unable to access cookie info until refresh, even though cookie is set on separate page

On my website I’m trying to echo a string if a cookie has been set on another page. However it only checks if the cookie isset after I’ve refreshed the page. Here is my code:

question/5.php (this part works fine)

if(isset($_COOKIE['intoGame'])){
}
else{
$intoGameGet = "into";
setcookie('intoGame', $intoGameGet, time() + (86400 * 14), '/');   
}

This cookie is set on the 5.php page. Then on index php I try to access the cookie. This is where the problem happens.

if (!isset($_COOKIE["intoGame"])){  //(only checks this after 1 refresh)
$content1 = 'the cookie has not been set';

}
else{
$content1 = 'hello question 5 answered';
echo $_COOKIE["intoGame"];
}

Then lower on the page I echo out $content1. If the cookie has been set, it should echo ‘hello question 5 answered’. However it does not do this unless I refresh the page.

In simple terms: I set the cookie on (page1). Then on (page2) I try to access the cookies previously set. However I need to refresh the page on (page2) before I see the cookie.

Any help would be appreciated.

Use your browser developer tools to examine the headers passed for the second page. Is the cookie info in a header there?

Yes, the cookie info is in the header when coming to the page. However the isset function doesn’t seem to check until I refresh the page.

I’m not exactly clear on the process here. Can you check that I’m understanding correctly?

  1. User browses to question/5.php and cookie is set
  2. User goes to index.php… how? Is it a header('Location: /index.php'); type thing or has the user clicked a link?
  3. User is now on index.php but you can’t read the cookie value yet at the server side
  4. User refreshes and now the cookie information is available

Am I right in understanding the process? What is the answer to 2.?

Site is a question game. Starts on index.php. Then goes to 1.php, then 2.php, etc, until reaching the end of the questions. Some users don’t finish the question game in one sitting, so they bookmark page and come back later (to index.php). I then need to display different site information allowing user to continue.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.