Reputation: 308
I am new to cookies, and tried to search for my problem, but couldn't find it.
My code:
index.php
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
When you open the page in the browser, the bottom part of the php code is executed, there shouldn't be a cookie 'time' so the body will be echoed with the onload="toggleoverlay()". This all works fine.
then when i click on the submit button to accepts the cookies, the page is reload, and the upper part of my php code is executed, a cookie named 'time' is created with the current time.
then the bottom part should be executed, but it still echos the body with the onload, even though i just created the cookie.
i also get the error when i'm trying to echo the cookie (saying the cookie does not exist). when i reload the page again manually then it works. But this is very frustrating since you need to accepts the cookie. then the page gets reloaded, and the overlay opens again.
I think this is because it takes some time creating the cookie and by then the other code has already been executed, but does anyone know how to fix this?
Thanks in advance.
Upvotes: 0
Views: 803
Reputation: 674
The cookie is not set until the response is sent back to the client (browser). It is not available in your PHP until the next request from the client after that.
You could do next.
<?php
$cookie_set = isset($_COOKIE['time']);
if (!$cookie_set && isset($_GET['submit']) {
setcookie('time', date('Y/m/d H:i:s'), time() + 3600);
$cookie_set = true;
}
if ($cookie_set) {
echo '<body>';
} else {
echo '<body onload="toggleOverlay(0)">';
}
Upvotes: 1
Reputation: 308
I have found a semi-solution, if the page is submitted, the page is reloaded, then after the cookie is created, i reload the page again en change the index.php?submit to index.php
like this
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
header("Refresh:0; url=index.php");
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
Like this it works, but it is not the best solution.
Upvotes: 0