32

I am making a visitor counting system for user posts to show the most viewed posts on homepage. I have a visitor counting system now but all it registers a view at every page refresh. I cannot use Google Analytics.

What I need is a visitor counter which only counts the unique visitors. In my case, unique means one person can only view a post in a day? Even a week might work, I think. Can you write that php code in here? You can give me a link to some good tutorials too if you like too.

This is what the code needs to do (or equivalent):

  1. Once the page loads, check if the visitor is new or old(I have no idea how to do it .. )
  2. If he is old, ignore him
  3. If he is new, in mysql, views = views + 1
4

5 回答 5

26

这是一个很好的教程,它是你需要的。(来源:coursesweb.net/php-mysql

注册并显示在线用户和访问者

使用 MySQL 表计算在线用户和访问者

在本教程中,您可以学习如何注册、统计和在您的网页中显示在线用户和访问者的数量。原理是这样的:每个用户/访问者都注册在一个文本文件或数据库中。每次访问网站的一个页面时,php 脚本都会删除所有超过某个时间(例如 2 分钟)的记录,添加当前用户/访问者并获取剩余的记录数以显示。

您可以将在线用户和访问者存储在服务器上的文件或 MySQL 表中。在这种情况下,我认为使用文本文件添加和读取记录比将它们存储到需要更多请求的 MySQL 表中更快。

首先介绍了在服务器上以文本文件记录的方法,而不是MySQL表的方法。

要下载包含本教程中提供的脚本的文件,请单击 ->统计在线用户和访问者

• 两个脚本都可以包含在“ .php”文件(带有include()或“ .html”文件(带有<script>中,如本页底部的示例所示;但服务器必须运行 PHP。

将在线用户和访问者存储在文本文件中

要使用 PHP 在服务器上的文件中添加记录,您必须为该文件设置 CHMOD 0766(或 CHMOD 0777)权限,以便 PHP 可以在其中写入数据。

  1. 在您的服务器上创建一个文本文件(例如,命名userson.txt)并授予它CHMOD 0777权限(在您的 FTP 应用程序中,右键单击该文件,选择属性,然后选择ReadWriteExecute选项)。
  2. 创建一个包含usersontxt.php以下代码的 PHP 文件(名为 ),然后将此 php 文件复制到与userson.txt.

的代码usersontxt.php

<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. 如果您想将上述脚本包含在“.php”文件中,请在您要显示在线用户和访问者数量的位置添加以下代码:

4.要在“.html”文件中显示在线访问者/用户的数量,请使用以下代码:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

此脚本(以及下面介绍的其他脚本)与 $_SESSION 一起使用。在您使用它的 PHP 文件的开头,您必须添加: session_start();。使用 MySQL 表计算在线用户和访问者

要在 MySQL 表中注册、统计和显示在线访问者和用户的数量,需要执行三个 SQL 查询: 删除超过一定时间的记录。使用新用户 /visitor 插入一行,或者,如果已插入,则更新其列中的时间戳。选择剩余的行。这是使用 MySQL 表(名为“userson”)存储和显示在线用户和访问者的脚本的代码。

  1. 首先我们创建“userson”表,有 2 列(uvon,dt)。在“uvon”列中存储了用户名(如果已登录)或访问者的 IP。在“dt”列中存储了一个数字,其中包含访问页面时的时间戳(Unix 时间)。
  • 在 php 文件中添加以下代码(例如,名为“create_userson.php”):

代码create_userson.php

<?php
header('Content-type: text/html; charset=utf-8');

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
 `uvon` VARCHAR(32) PRIMARY KEY,
 `dt` INT(10) UNSIGNED NOT NULL
 ) CHARACTER SET utf8 COLLATE utf8_general_ci"; 

// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;

$conn->close();
?>
  1. 现在我们创建在表中插入、删除和选择数据的脚本userson(有关代码的解释,请参见脚本中的注释)。
  • 在另一个 php 文件(名为 )中添加以下代码usersmysql.php: 在这两个文件中,您必须在变量中添加您的个人数据以连接到 MySQL 数据库:$host$user$pass$dbname.

usersmysql.php 的代码:

<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();         // start Session, if not already started

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-';         // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the rows with visitors
$dt = time();                                    // current timestamp
$timeon = 120;             // number of secconds to keep a user online
$nrvst = 0;                                     // to store the number of visitors
$nrusr = 0;                                     // to store the number of usersrs
$usron = '';                                    // to store the name of logged users

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";

// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
  while($row = $result->fetch_assoc()) {
    if(preg_match($rgxvst, $row['uvon'])) $nrvst++;       // increment the visitors
    else {
      $nrusr++;                   // increment the users
      $usron .= '<br/> - <i>'.$row['uvon']. '</i>';          // stores the user's name
    }
  }
}

$conn->close();                  // close the MySQL connection

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. 在服务器上创建这两个 php 文件后,在浏览器上运行“create_userson.php”以创建“userson”表。

  2. 将文件包含在usersmysql.php要显示在线用户和访问者数量的 php 文件中。

  3. 或者,如果要将其插入“.html”文件,请添加以下代码:

使用这些脚本的示例

• 在 php 文件中包含“usersontxt.php”:

<!doctype html>

柜台在线用户和访客

• 在 html 文件中包含“usersmysql.php”:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

两个脚本(将数据存储在服务器上的文本文件或 MySQL 表中)将显示如下结果:在线:5

访客:3 用户:2

  • 马尔普罗
  • 马吕斯
于 2013-09-14T08:34:20.170 回答
20

独特的观点总是一个难以破解的难题。检查 IP 可能有效,但一个 IP 可以由多个用户共享。cookie 可能是一个可行的选项,但 cookie 可能会过期或被客户端修改。

在您的情况下,如果 cookie 被修改,这似乎不是一个大问题,所以我建议在这种情况下使用 cookie。当页面加载时,检查是否有cookie,如果没有,创建一个并为views添加+1。如果已设置,请不要执行 +1。

将 cookie 的到期日期设置为您想要的任何日期,一周或一天,如果这是您想要的,它将在该时间之后到期。到期后,将再次成为唯一用户!


编辑:
认为在此处添加此通知可能是个好主意......
因为大约在 2016 年底,IP 地址(静态或动态)在欧盟被视为个人数据。
这意味着您只能在有充分理由的情况下存储 IP 地址(而且我不确定跟踪视图是否是一个很好的理由)。因此,如果您打算存储访问者的 IP 地址,我建议您使用不可逆转的算法对其进行散列或加密,以确保您没有违反任何法律(尤其是在 GDPR 法律实施之后)。

于 2013-09-14T08:31:52.110 回答
7

要找出用户是新用户还是旧用户,请获取用户 IP。

为 IP 及其访问时间戳创建一个表。

检查如果IP 不存在time()-saved_timestamp > 60*60*24(1 天),将 IP 的时间戳编辑为time()(表示现在)并增加您的视图之一。

否则,什么也不做。

仅供参考:用户 IP 存储在$_SERVER['REMOTE_ADDR']变量

于 2013-09-14T08:46:40.790 回答
7

我已经编辑了“最佳答案”代码,尽管我发现了一个有用的东西丢失了。如果用户使用代理,或者服务器安装了 nginx 作为代理反向器,这也将跟踪用户的 ip。

我将此代码添加到函数顶部的脚本中:

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

之后我编辑了他的代码。

找到显示以下内容的行:

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

并将其替换为:

$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;

这将起作用。

如果发生任何事情,这是完整的代码:

<?php

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result

尚未在 Sql 脚本上对此进行测试。

于 2015-10-23T10:16:40.283 回答
3
$user_ip=$_SERVER['REMOTE_ADDR'];

$check_ip = mysql_query("select userip from pageview where page='yourpage'  and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{

}
else
{
  $insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");

  $updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}

来自talkerscode官方教程的代码,如果你有任何问题http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php

于 2016-03-08T15:17:05.753 回答