Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie page counter in php

Tags:

php

cookies

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

like image 702
Steffan Harris Avatar asked Oct 31 '11 19:10

Steffan Harris


1 Answers

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.

like image 153
jprofitt Avatar answered Sep 21 '22 23:09

jprofitt