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,ti开发者_开发知识库me()+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!
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. 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:
if(isset($_COOKIE["counter_cookie"]))
{
$counter = $_COOKIE["counter_cookie"];
}
else
{
$counter = 0;
}
$counter++
setcookie("counter_cookie", $counter ,time()+40);
精彩评论