用于跟踪唯一页面浏览量的 PHP 会话 [英] PHP session for tracking unique page views

查看:19
本文介绍了用于跟踪唯一页面浏览量的 PHP 会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用会话来跟踪唯一的页面浏览量.我知道,这不是一种非常可靠的方法,但足以满足我的需求.

I want to use sessions to track unique page views. Not a very robust method, I know, but sufficient for what I want to do.

在第一页加载时,会话变量被设置,数据库中的一个字段增加.在随后的页面访问中,它不会增加,因为增加的条件是未设置会话变量.

On the first page load the session variable is set and a field in the database increments. On subsequent page views it does not increment, because the increment is conditional on the session variable not being set.

这是我的代码:

$pagenumber = 1;

//other stuff here...

session_start();

if (!isset($_SESSION[$pagenumber])) {
    $storeview = mysqli_query($dbconnect, "UPDATE tblcount SET views=views+1 WHERE id='$pagenumber'");
    $_SESSION[$pagenumber] = $pagenumber;
}
echo $_SESSION[$pagenumber];

$Recordset1 = mysqli_query($dbconnect, "SELECT views FROM tblcount WHERE id = '$pagenumber'");
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);

echo "Viewed ".$row_Recordset1['views']." times";

第一个回声仅用于测试.它在页面刷新时很好地回显了该值,并且增量第一次起作用,但是视图计数在每次页面刷新时继续增加,这是不应该的.我不明白为什么.

The first echo is only there for testing. It echoes the value just fine on page refresh and the increment works the first time, but the view count continues to increment on every page refresh, which it shouldn't. I can't see why.

我发现了一个类似的问题:PHP:使用 cookie 对特定项目的唯一访问/点击/ip 但我在那里提供的解决方案中遇到了类似的问题.

I found a similar question: PHP: Unique visits/hits to specific items using cookies/ip but I ran into a similar issue with the solution offered there.

感谢帮助!

推荐答案

问题:

  1. 您每次更新 tblCount 次,因为每次脚本完成时您的会话都会关闭.SO:将 session_start() 调用作为代码中的第一行.
  2. 不允许将整数设置为 $_SESSION 变量.因此,如果您设置 $_SESSION[$pagenumber] = 'something',那么您将获得以下通知:
  1. You are updating in tblCount EACH time, because your session is closed each time your script finishes. SO: Put the session_start()call as the FIRST LINE in code.
  2. It's not permitted to set an integer as $_SESSION variable. So if you set $_SESSION[$pagenumber] = 'something', then you gain the following notice:

<块引用>

( ! ) 注意:Unknown:在第 0 行的 Unknown 中跳过数字键 1

相当……无法理解.有关详细信息,请参阅此答案.

( ! ) Notice: Unknown: Skipping numeric key 1 in Unknown on line 0

将您的 $pagenumber 添加为数组(此处为 pagenumbers)中的索引,并将该数组添加到 $_SESSION 变量中.没有通知了.

Quite... not understandable. For details see this answer.

Add your $pagenumber as index in an array (here pagenumbers) and that array inside the $_SESSION variable. No notice anymore.

';

注意:我用我的函数来测试.它们只是替换了您的数据库处理代码.

Note: I used my functions to test. They just replace your db-processing code.

这篇关于用于跟踪唯一页面浏览量的 PHP 会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆