I'am trying to set a cookie in a php file (yesterday it worked, today it does not)
I made the cookie and now i'm trying to delete is by setting it to a null-value. Still the cookie is not being made.
I already deleted the cookies in my browser aswell.
Can someone help me?
setcookie("winkelwagen", "", '/');
if(!isset($_COOKIE["winkelwagen"])) {
echo "<br>Cookie is not set!";
} else {
echo "<br>Cookie '" . $_COOKIE["winkelwagen"] . "' is set!";
echo "<br>Value is: " . $_COOKIE["winkelwagen"];
}
I'm getting "Cookie is not set" as output
-
FYI: You cannot access cookie on the same request after setting it. Cookies are sent by browser as a part of HTTP Request Headers. And Cookies are sent by server as a part of HTTP Response Headers. So your HTTP request will not have the cookie which you are just setting in the response.ksg91– ksg912015年04月06日 07:37:37 +00:00Commented Apr 6, 2015 at 7:37
-
After a page reload it also says 'cookie not set'user3475797– user34757972015年04月06日 07:45:36 +00:00Commented Apr 6, 2015 at 7:45
2 Answers 2
This is supposed to fail / the expected behaviour:
setcookie("winkelwagen", "", '/');
if(!isset($_COOKIE["winkelwagen"])) {
echo "<br>Cookie is not set!";
}
According to the manual (emphasis added by me):
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
So your cookie will never be available when you set it, it will be available on the next page you load.
14 Comments
You've made a mistake, you didn't setlife time (it is third parameter), but you set there path '/', which must be the fourth parameter. Also cookie doesn't set with empty value.
From the docs:
If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.
Use this:
setcookie("winkelwagen", "some_value",time() + (86400 * 30), '/') //for eaxmle 86400 = 1 day