Search code examples
phpcookiessetcookie

PHP COOKIE visits counter increases by 2


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?


Solution

  • 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...