Reputation: 1864
I am using this code to set a cookie and then see if they exist
setcookie("token", "value", time()+60*60*24*100, "/");
setcookie("secret", "value", time()+60*60*24*100, "/");
setcookie("key", "value", time()+60*60*24*100, "/");
if (!isset($_COOKIE['token']) || !isset($_COOKIE['secret']) || !isset($_COOKIE['key'])) {
// do something because one of the cookies were not set
}
Even though all three of the cookies were set in my browser, it still runs the if()
statement. Via the process of elimination I have discovered the middle cookie !isset($_COOKIE['secret'])
seems to cause the if()
statement to run even though the cookie secret
was set in my browser. The script says it has not been set when I look at my browser and it has been set. Can you think of any reason why php is saying it wasn't set?
Upvotes: 0
Views: 59376
Reputation: 77
as my testing,we can't use cookies in same time.if you set cookies. you need to reload page to grab those. put like this
if (!isset($_COOKIE['token'])) { setcookie("token", "value", time()+60*60*24*100, "/"); //this set cookies for first time }
Upvotes: 0
Reputation: 7887
use
if(true === array_key_exists('secret', $_COOKIE) && strlen($_COOKIE['secret']) > 0) {
}
Upvotes: 0
Reputation: 160853
setcookie
only defines a cookie to be sent along with the rest of the HTTP headers, and they can be accessed on the next page load with the $_COOKIE
. With your code, the HTTP headers are not be sent.
You just need setcookie
when a cookie is not set. Like:
if (!isset($_COOKIE['token'])) {
setcookie("token", "value", time()+60*60*24*100, "/");
}
Upvotes: 8