使用 PHP 增加 Cookie(初学者问题)
我以前用过session,但从来没有用过cookies。我想使用 cookie 有两个原因:
1)这是需要学习的新东西
2)我想让 cookie 在一个小时左右过期(我知道在代码示例中它会在 40 秒后过期)
我正在尝试编写一个基本的 if 语句,
if($counter=="1") { //do this second
}
elseif ($counter >="2") { //do this every time after the first and second
}
else {// this is the first action as counter is zero
}
这是我用来设置 cookie 的代码:
// if cookie doesnt exsist, set the default
if(!isset($_COOKIE["counter_cookie"])) {
$counter = setcookie("counter_cookie", 0 ,time()+40);
}
// increment it
$counter++;
// save it
setcookie("counter_cookie", $counter,time()+40);
$counter = $_COOKIE["counter_cookie"];
问题是计数器将从 0 设置为 1,但不会从 1 设置为 2,依此类推。任何帮助都会很棒我知道这是一个非常简单的愚蠢问题:|
谢谢!
I have used sessions before but never cookies. I would like to use cookies for two reasons:
1) it's something new to learn
2) I would like to have the cookie expire in an hour or so (i know in the code example it expires in 40 sec)
I am trying to write a basic if statement that
if($counter=="1") { //do this second
}
elseif ($counter >="2") { //do this every time after the first and second
}
else {// this is the first action as counter is zero
}
Here is the code I'm using to set the cookie:
// if cookie doesnt exsist, set the default
if(!isset($_COOKIE["counter_cookie"])) {
$counter = setcookie("counter_cookie", 0 ,time()+40);
}
// increment it
$counter++;
// save it
setcookie("counter_cookie", $counter,time()+40);
$counter = $_COOKIE["counter_cookie"];
The problem is that the counter will be set from 0 to 1 but won't be set from 1 to 2 and so on. Any help would be great I know this is a really simple stupid question :|
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该问题很可能与这一行有关:
您似乎期望 setcookie 返回一个值,但这不会发生。相反,setcookie 只会在成功时返回布尔值 true,在失败时返回 false。
http://php.net/manual/en/function.setcookie.php
你可以尝试这样重写以达到想要的效果:
The problem is most likely related to this line:
It appears you are expecting setcookie to return a value, but that isn't going to happen. Instead, setcookie will simply return a boolean true on success and false on failure.
http://php.net/manual/en/function.setcookie.php
You could try rewriting it like this to achieve the desired effect: