简体   繁体   English

如何计算页数视图的数量?

[英]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. 问题出现在我的代码中,当用户访问该页面时,计数器增加1,这是可以的,但是当用户多次刷新页面时,计数器会不断增加。 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. 最好的方法是使用谷歌分析等一些js跟踪器 .

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. 如果您不想跟踪页面刷新,可以使用cookie会话来存储上次发生增量的时间戳,因此您不会增加直到它过期。

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). 但是,如果用户已禁用cookie,则此操作无效,因为没有cookie支持使浏览器无法保留会话ID(这是会话工作所必需的)。 Thus refreshing in browser w/o cookies will still yield too many clicks. 因此,在没有cookie的浏览器中刷新仍然会产生太多的点击。

To deal with these cases, you can remember IPs ( $_SERVER['REMOTE_ADDR'] ) and check if given IP has visited your page. 要处理这些情况,您可以记住IP( $_SERVER['REMOTE_ADDR'] )并检查给定的IP是否已访问过您的页面。 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 . 最佳选择是使用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. 您可以使用cookies。 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. 在访问时检查是否设置了cookie,如果没有为页面设置cookie(cookie的生命周期可能根据你的需要而有所不同),只有在没有设置cookie的情况下才更新计数器。 If you need counter to be complex - than it is better to use something like Google Analytics. 如果您需要反复杂乱 - 而不是使用像谷歌分析这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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