向php页面添加计数器以计算唯一身份访问者 [英] adding counter to php page to count the unique visitors

查看:103
本文介绍了向php页面添加计数器以计算唯一身份访问者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网页中添加一个计数器来统计访问者的数量。
但是我的问题是,当我刷新页面时,计数器增加1..i,我希望仅当具有另一个ip的新访问者到达我的网页时,该计数器才会增加。
这是我的代码。
对不起,我的英语不强

I want to add a counter in my webpage which counts the number of visitors. But my problem is that when i refresh my page ,counter increases by 1..i want that counter increases only when a new visitor with another ip reaches to my webpage. here are my codes.. Sorry for my weak english

index.php

   <?php
session_start();

$ip = $_SERVER['REMOTE_ADDR']; 
$_SESSION['current_user'] = $ip;


if(isset($_SESSION['current_user']))
{
    $count = file_get_contents("counter.txt");
    $count = trim($count);
    $fl = fopen("counter.txt","w+");
    fwrite($fl,$count);
    fclose($fl);


}

else
{
    $count = file_get_contents("counter.txt");
    $count = trim($count);
    $count = $count + 1;
    $fl = fopen("counter.txt","w+");
    fwrite($fl,$count);
    fclose($fl);

}


推荐答案

作为数据库基于解决方案的方法不是首选,您可以尝试以下基于文件的解决方案来计算唯一身份访问者。您已经在代码中使用了 counter.txt 文件。

As database based solution is not preferred, You can try the following file based solution for counting unique visitor. You already have used counter.txt file in your code.

我尝试使用与您使用的相同的文件。就我而言,我将IP地址存储在该文件中。我使用base64编码功能只是为了隐藏IP地址。将文件保存在安全的位置总是好事。如果该文件丢失,则唯一的访问者IP将丢失。参见下面的函数:

I tried to use the same file that you have used. In my case I am storing IP address in that file. I have used base64 encoding function just to hide the IP address. It is always good to keep that file in a safe place. If that file is lost then the unique visitor IPs will be lost. See the function below:

function getUniqueVisitorCount($ip)
{
    session_start();
    if(!isset($_SESSION['current_user']))
    {
        $file = 'counter.txt';
        if(!$data = @file_get_contents($file))
        {
            file_put_contents($file, base64_encode($ip));
            $_SESSION['visitor_count'] = 1;
        }
        else{
            $decodedData = base64_decode($data);
            $ipList      = explode(';', $decodedData);

            if(!in_array($ip, $ipList)){
              array_push($ipList, $ip);
              file_put_contents($file, base64_encode(implode(';', $ipList)));
            }
            $_SESSION['visitor_count'] = count($ipList);
        }
        $_SESSION['current_user'] = $ip;
    }
}


$ip = '192.168.1.210'; // $_SERVER['REMOTE_ADDR'];
getUniqueVisitorCount($ip);
echo 'Unique visitor count: ' . $_SESSION['visitor_count'];


Unique visitor count: 2

这篇关于向php页面添加计数器以计算唯一身份访问者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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