Joe
Joe

Reputation: 8262

Setting Cookie not working

Isn't this suppose to increment every time I load the page? Cause its not doing that its ending at 2 AND when I open other pages with the code in place it tells me that $_COOKIE['count'] is not set.

if(!isset($_COOKIE['count'])){
    setcookie("count", 1, time() + 31536000);
} else {
    setcookie("count", $_COOKIE['count']++, time() + 31536000);
}

Ok so answers to the incrementing problem thanks its fixed +1's for you guys BUT the second problem is still there which is:

Ok so now its incrementing properly BUT problem 2 is still the same for 1 page e.g. index.php the cookie has a value of 15 when I go to the other page e.g. second.php the value is 5 when I refresh its 6 when I go back to index.php the value is 16. any ideas?

Upvotes: 0

Views: 78

Answers (3)

Joe
Joe

Reputation: 8262

Ok so I had 2 problems in this. First is with the increment part (but I was just testing if the value was changing didn't really needed the increment part) AND the second one was the mix up between pages. . why different pages had different values that didn't stack. The answer to that problem was . . I didn't set a value for the path parameter, I didn't realize it was needed till then. I think it bugged up because of my url rewrites not sure though just a hunch. But anyway the path param fixed it for me.

If any of you get into the same trouble simply add a value to path param while setting your cookies like so:

setcookie("cookiename", $cookievalue, $cookielifespan , '/');

If the path param is set to '/' the cookie will be available within the entire domain

For more details just check the manual, Cheers!

Upvotes: 0

Tasos Bitsios
Tasos Bitsios

Reputation: 2789

$a = 1;
$b = $a++; //with the $a++ syntax, $b is set to $a's old value first, 
//and then $a is increased
//$b = 1, $a = 2

$a = 1;
$b = ++$a //with the ++$a syntax,  $a is incremented first 
//and then $b is set to (incremented) $a
//$b = 2, $a = 2

So, you need to do ++$_COOKIE['count'], because you want to increase the cookie value before it is passed to setcookie.

Upvotes: 2

user2680766
user2680766

Reputation:

Change $_COOKIE['count']++ to either $_COOKIE['count']+1 or ++$_COOKIE['count']and the code will work perfectly.

Upvotes: 5

Related Questions