user2354209
user2354209

Reputation: 9

How do i make a count that counts the number of page-views?

I want to count the total number of pages that have been visited by a user. The problem is in my code when a user visits the page the counter increases by 1, which is okay, but when the user refreshes the page many times the counter keeps increasing. I want to increase the counter on first visit of a user, but not when they refresh the page. How do I solve this problem?

Upvotes: 0

Views: 2061

Answers (4)

Sergiy T.
Sergiy T.

Reputation: 1453

You may use cookies for this. On visit check if cookie is set, if not than set cookie for the page (cookie lifetime may vary depending on what you want), update counter only if cookie is not set. If you need counter to be complex - than it is better to use something like Google Analytics.

Upvotes: 0

rr-
rr-

Reputation: 14811

Use sessions.

<?php
session_start();
if (!isset($_SESSION['visited']))
{
    $_SESSION['visited'] = 1;
    //increase the page view counter...
}

This, however, won't work if user has disabled cookies, since no cookie support makes browser unable to keep session ID (which is necessary for sessions to work). Thus refreshing in browser w/o cookies will still yield too many clicks.

To deal with these cases, you can remember IPs ($_SERVER['REMOTE_ADDR']) and check if given IP has visited your page. Note that this solution is still vulnerable -- "sophisticated" attacks that rely on using proxy servers will still be able to count too many clicks.

The best option is to use external tracking system like Google Analytics.

Upvotes: 1

tux
tux

Reputation: 1287

Try using a session, a very simple example would be:

<?php
session_start();
$counter = 0;

if(! isset($_SESSION['visited'])):
        $counter +=1;
        $_SESSION['visited'] = TRUE;
        $_SESSION['counter'] = $counter;
endif;
echo $_SESSION['counter'];
?>

Upvotes: 0

mr. Pavlikov
mr. Pavlikov

Reputation: 1012

Best way is to use some js tracker like Google Analytics..

If you do not want to track page refresh, you can use cookie or session to store timestamp of last time the increment happened, so you do not increment till it expires.

Upvotes: 1

Related Questions