I have this code here:
setcookie('visitcount',1+$_COOKIE['visitcount'],time()+60*60); $visitcount = $_COOKIE['visitcount']; print "Number of views: ".$visitcount;
What I’m trying to do is keeping track of the page views the current viewer using cookie. I’m a bit confused with this code because when the web visitor views the webpage for the first time, the result came back saying “Number of views: 0”, when it should be “Number of views: 1”.
Why is that the case? I thought with setcookie code above, the $visitcount variable should have a value of one. But it isn’t so??
Advertisement
Answer
This line:
setcookie('visitcount',1+$_COOKIE['visitcount'],time()+60*60);
is sending the value “1+$_COOKIE[‘visitcount’]” (which is = to 1) to the client.
The next line, $_COOKIE[‘visitcount’] is still the initial value (i.e. ‘0’ the first time), because it comes from the request. You need to receive the updated COOKIE from the next request to get the result of the increment.