Reputation: 57
I want to store a cookie, using PHP, containing the number of pageviews for a user. This is my code:
if (!isset($_COOKIE['visits'])) $_COOKIE['visits'] = 0;
$visited = $_COOKIE['visits'] + 1;
setcookie('visits', $visited, time() + $h * 3600, "/");
For some reason, the counter increases by 2 instead of 1. Where is the bug?
Upvotes: 0
Views: 444
Reputation: 1240
First: Use brackets! They are there for a good reason, then your if would expand to:
if (!isset($_COOKIE['visits'])){
$visited = 0;
}else{
$visited = $_COOKIE['visits'] + 1;
}
setcookie('visits', $visited, time() + $h * 3600, "/");
Notice, that I have exchanged $_COOKIE['vistits']
with $visited
. In the next call, $_COOKIE
will be filled, there is no need to fill it by yourself.
Here could be your problem: When do you read the $_COOKIE
? Possible to an wrong time...
Upvotes: 2
Reputation: 57
Sorry, I fixed it, was a problem with
add_action('init', 'load_function'); in wordpress.
Upvotes: 0