I am implementing a php page counter that will keep track of each time the user visits this page until the browser is closed. I am checking to see if the cookie is set, if it is. Then I am increment it and reset its value. But the problem I am having is that the counter is always at two, why is this?
<html>
<head>
<title>Count Page Access</title>
</head>
<body>
<?php
if (!isset($_COOKIE['count']))
{
?>
Welcome! This is the first time you have viewed this page.
<?php
$cookie = 1;
setcookie("count", $cookie);
}
else
{
$cookie = $_COOKIE['count']++;
setcookie("count", $cookie);
?>
You have viewed this page <?= $_COOKIE['count'] ?> times.
<?php }// end else ?>
</body>
</html>
Edit: Thanks everyone, I did the pre increment thing and got it to work
This is happening because of the ++
being used as a post-increment instead of a pre-increment. Essentially what is happening is you're saying, "set $cookie
to the value of $_COOKIE['count']
, and then increment $_COOKIE['count']
. This means that each time you set it you're only actually making $cookie
equal 1, and even though $_COOKIE['count']
is showing it as 2, the actual cookie you send will only equal 1. If you do $cookie = ++$_COOKIE['count'];
you should get the correct result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With