【问题标题】:How to change the value which is being counted in this unique hits counter?如何更改此唯一命中计数器中的计数值?
【发布时间】:2011-04-26 22:06:29
【问题描述】:

我有这个独特的计数器:

<?php
$log = 'hits.log';

$IP = getenv (REMOTE_ADDR);
$add = true;
$hits = 0;

if (!file_exists ($log)) {
    echo "Error: $log does not exist.";
    exit;
}

$h = fopen ($log, 'r');
while (!feof ($h)) {
    $line = fgets ($h, 4096);
    $line = trim ($line);
    if ($line != '')
        $hits++;

    if ($line == $IP)
        $add = false;
}

fclose($h);

if ($add == true) {
    $h = fopen ($log, 'a');
    fwrite($h, "
$IP");
    fclose($h);
    $hits++;
}

echo $hits;
?>

但它只计算我放置的页面获得的唯一点击量。因此,如果我将此代码放在http://site.com 上,它只会显示http://site.com 的唯一命中。我想知道我是否可以在代码中添加或编辑某些内容以使脚本计算不同页面的唯一点击,但将其显示在它所在的页面上(跟踪http://site.com/yay,但显示点击http://site.com)任何人知道该怎么做吗?谢谢。

【问题讨论】:

  • 你应该在你想监控的所有页面中运行它,如果你不需要打印它,删除最后一个echo。但是,你知道,这是一种非常非常糟糕的计算唯一性的方法——你每次都阅读整个日志!
  • 真的吗?那么有没有更好的方法?
  • 方法有很多。最常见的 - 使用 cookie 或会话来“标记”用户。
  • 浏览器关闭后会话会被删除,你如何用 cookie 做到这一点?
  • 不,他们没有。 cookie 怎么样 - 检查 cookie 是否存在,如果不存在 - 使用当前时间戳设置 cookie 24 小时(如果是 - 检查保存的时间戳早于 24 小时)

标签: php counter


【解决方案1】:

仅举例(在 cmets 中要求)

<?php
$log = 'hits.log';

if (!file_exists ($log)) {
    echo "Error: $log does not exist.";
    exit;
}

$hits = (int) file_get_contents($log);

if (!isset($_COOKIE['last_visit']) or date('d.m.Y', (int) $_COOKIE['last_visit']) != date('d.m.Y')) {
    setcookie('last_visit', time(), 90000); //of course you can encode it for security reason

    $hits++;
    file_put_contents($log, $hits);
}

echo $hits;
?>

这仍然不是统计用户数的最佳方式。

【讨论】:

  • 谢谢,但我仍然不知道如何更改正在计数的值。
猜你喜欢
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多