1

I needed to have a counter on my page that would increment each time the website is visited, pretty simple huh, but...

I have run into a problem, for some reason my page counter doesn't increment at all even though the code seems to be correct.

<?php
if (!isset($_COOKIE["visitCount"])) {
    setcookie("visitCount", 1);
} else {
    $_COOKIE["visitCount"]++;
}

echo $_COOKIE["visitCount"];

It always stays at 2, no matter how many times i refresh the page, help would be greatly appreciated.

hakre
  • 193,403
  • 52
  • 435
  • 836
user2209644
  • 701
  • 1
  • 9
  • 21
  • Do you want to count the page visits or the number of visits per user? – Hannoun Yassir Nov 03 '13 at 13:53
  • I just want the cookie visitCount to increment by 1 each time the page is loaded – user2209644 Nov 03 '13 at 13:56
  • Exactly this has been asked not too long ago. But more important is that you understand how to set the error reporting for logging: To the highest level and in php.ini. See as well: [How to get useful error messages in PHP?](http://stackoverflow.com/a/14504459/367456) – hakre Nov 03 '13 at 14:11

2 Answers2

3

You need to set the variable before you can access it for the first time.

So you need to set it, before you use it in case it is not yet set.

If set, you also need to sanitize/validate the input:

<?php

$name = "visitCount";

if (!isset($_COOKIE[$name])) {
    $_COOKIE[$name] = 0;
}
$_COOKIE[$name] = 1 + (int) max(0, $_COOKIE[$name]);
$result = setcookie($name, $_COOKIE[$name]);
if (!$result) {
    throw new RuntimeException("Failed to set cookie \"$name\"");
}

To easier spot those errors, enable error reporting for developing:

Community
  • 1
  • 1
Krish R
  • 22,583
  • 7
  • 50
  • 59
1

try this

setcookie('visitCount', isset($_COOKIE['visitCount']) ? $_COOKIE['visitCount']++ : 1);
Nextar
  • 1,088
  • 2
  • 12
  • 26