[英]Incrmenting a Cookies with PHP (Beginner Question)
I have used sessions before but never cookies. 我之前使用过会话,但从未使用过cookie。 I would like to use cookies for two reasons:
我想使用Cookie有两个原因:
1) it's something new to learn 1)这是新知识
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) 2)我想让Cookie在一个小时左右过期(我在代码示例中知道它在40秒后过期)
I am trying to write a basic if statement that 我正在尝试写一个基本的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
}
Here is the code I'm using to set the cookie: 这是我用来设置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. 问题是计数器将设置为0到1,但不会设置为1到2,依此类推。 Any help would be great I know this is a really simple stupid question :|
任何帮助都会很棒,我知道这是一个非常简单的愚蠢问题:
Thanks! 谢谢!
The problem is most likely related to this line: 问题很可能与以下行有关:
$counter = setcookie("counter_cookie", 0 ,time()+40);
It appears you are expecting setcookie to return a value, but that isn't going to happen. 看来您期望setcookie返回一个值,但这不会发生。 Instead, setcookie will simply return a boolean true on success and false on failure.
相反,setcookie将仅在成功时返回布尔值true,而在失败时返回false。
http://php.net/manual/en/function.setcookie.php http://php.net/manual/zh/function.setcookie.php
You could try rewriting it like this to achieve the desired effect: 您可以尝试像这样重写它以获得所需的效果:
if(isset($_COOKIE["counter_cookie"]))
{
$counter = $_COOKIE["counter_cookie"];
}
else
{
$counter = 0;
}
$counter++
setcookie("counter_cookie", $counter ,time()+40);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.