why is this if statement always true? Even if i disable cookies in browser, it tells me "Cookie was set." print_r prints empty array, but it should say "No Cookie could be set, please allow cookies."
What's wrong with my code?
if (setcookie("Testcookie", "values of cookie", time()+3600*24)) // 1h*24 = 24hours
{
echo ("Cookie was set. ");
print_r ($_COOKIE);
} else {
echo("No Cookie could be set, please allow cookies.");
}
UPDATE: i tried this:
setcookie("Testcookie", "values of cookie", time()+3600*24); // 1h*24 = 24hours
if ((isset($_COOKIE)) && (!empty($_COOKIE))) { print_r($_COOKIE);} else {echo("No Cookie found.");}
This sets Cookie correctly, but it says "No Cookie found". After one reload it finds Cookie and print_r it. Why does it take one reload? I didn't send anything prior setcookie() call. Cookie IS set, but on first reload after deleting/enabling cookies it is not shown.
setcookie()
will always successfully create the cookie unless headers have already been sent (see Gumbo's link in the comments). It doesn't get feedback from the browser as to whether or not is was accepted. You need to set a flag that shows you attempted to set the cookie and then check to see if you get that cookie back on a fresh page request. Only then, when it is not present, can you be sure the cookie isn't being accepted.