user2209644
user2209644

Reputation: 711

Visit counter, with cookies not incrementing

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.

Upvotes: 1

Views: 2619

Answers (2)

Krish R
Krish R

Reputation: 22721

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:

Upvotes: 3

Nextar
Nextar

Reputation: 1098

try this

setcookie('visitCount', isset($_COOKIE['visitCount']) ? $_COOKIE['visitCount']++ : 1);

Upvotes: 1

Related Questions