Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

cookies - php $_COOKIE isset

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, "/");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...