Newbie question - Visits counter

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
earlsinclair2001
Forum Newbie
Posts: 2
Joined: Mon Sep 11, 2006 3:16 pm

Newbie question - Visits counter

Post by earlsinclair2001 »

Hi,

I'm a newbie in PHP and programmingin general, just started learning a couple days ago so please don't be mad if this question is too basic. I'm trying to create a page that will count the number of times a visitor has seen a page and store it in a cookie. I wrote this code:

Code: Select all

<?php
if (empty($_COOKIE['counter'])) setcookie('counter', 1, time()+60*60*24*365);
else {
$_COOKIE['counter'] = $_COOKIE['counter'] + 1;
}
?>
<html>
<head>
<title>Visits counter</title>
</head>
<body>
<p>You have visited this page <?php if (empty($_COOKIE['counter'])) echo "1"; else echo $_COOKIE['counter']; ?> times</p>
</body>
</html>
But it doesn't work properly. It adds 1 time but then it stops. So the first time you load this page it shows 1, the second time 2, but all subsequent times it only shows 2. Why doesn't it work?

Thanks.

Earl
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

Post by ambivalent »

It doesn't work because you have to use setcookie() each time you want to change the value stored in that cookie.

Code: Select all

$_COOKIE['counter'] = $_COOKIE['counter'] + 1;   //doesn't cut it
If you look at the cookie contents, you'll notice that it is always 1, the initial value you set.
User avatar
gkwhitworth
Forum Commoner
Posts: 85
Joined: Tue Sep 05, 2006 8:28 pm
Location: Wasilla, Alaska

Post by gkwhitworth »

yeah...you definately have to find a different alternative....one thing though, I would have the following function in place so you get unique visitors counted only:

Code: Select all

if (!isset($_COOKIE['counter'])) {
.. cookie code goes here ..
}

Remember that this only lasts as long as his session is stored or as long as the cookie is stored. If they delete their cookie than there is another hit for you.

Sorry I can't help out anymore but I am a newb as well.
earlsinclair2001
Forum Newbie
Posts: 2
Joined: Mon Sep 11, 2006 3:16 pm

Post by earlsinclair2001 »

Yes, I didn't realize I had to use setcookie again to change the value of it. I changed the code to this:

Code: Select all

<?php
if (empty($_COOKIE['counter'])) setcookie('counter', 1, time()+60*60*24*365);
else {
$count = $_COOKIE['counter'] +1;
setcookie('counter', $count, time()+60*60*24*365);
}
?>
<html>
<head>
<title></title>
</head>
<body>
<p>You have visited this page <?php if (empty($_COOKIE['counter'])) echo "1 time."; else echo $count, " times."; ?></p>
</body>
</html>
And now it works for what I intended to do. Thanks for the hints.
Post Reply