1

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.

  • When and where is 5.php called, and ditto for index.php? – kittykittybangbang Aug 18 '15 at 00:42
  • 1
    `setcookie()` does not update the `$_COOKIE` array. That always happens with the next page request. – mario Aug 18 '15 at 00:43
  • That's the way PHP is designed. You can't access the cookie in the same page request. You'll need to refresh it. – Darren Aug 18 '15 at 00:43
  • my site it funpoll(com). Index is the first page, then you go on to answer questions. 5.php corresponds to the fifth question page. – user3305089 Aug 18 '15 at 00:43
  • Right but the cookie is set 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. – user3305089 Aug 18 '15 at 00:45
  • mario, setcookie() was set on a different page. I'm trying to access the cookie on another page, but it's not showing until I refresh the page where I check isset. The question you refereed to as a duplicate is a completely different issue I think. – user3305089 Aug 18 '15 at 00:51

0 Answers0