简体   繁体   中英

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?

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.

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 .

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'];
?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM