Php 如何计算我的网站的唯一访问者?
我正在为用户帖子制作一个访客计数系统,以显示主页上浏览次数最多的帖子。我现在有一个访客计数系统,但它在每次页面刷新时都会注册一个视图。我不能使用谷歌分析 我需要的是一个访客柜台,它只统计唯一的访客。就我而言,“唯一”意味着一个人一天只能查看一篇文章?我想,一个星期也行。你能在这里写php代码吗?如果你也喜欢的话,你也可以给我一些好教程的链接 这就是代码需要执行的操作(或等效操作):Php 如何计算我的网站的唯一访问者?,php,mysql,counting,visitor-statistic,Php,Mysql,Counting,Visitor Statistic,我正在为用户帖子制作一个访客计数系统,以显示主页上浏览次数最多的帖子。我现在有一个访客计数系统,但它在每次页面刷新时都会注册一个视图。我不能使用谷歌分析 我需要的是一个访客柜台,它只统计唯一的访客。就我而言,“唯一”意味着一个人一天只能查看一篇文章?我想,一个星期也行。你能在这里写php代码吗?如果你也喜欢的话,你也可以给我一些好教程的链接 这就是代码需要执行的操作(或等效操作): 一旦页面加载,检查访客是新的还是旧的(我不知道怎么做…) 如果他老了,别理他 如果他是新来的,在mysql中,vi
独特的风景总是一个难题。 检查IP可能有效,但一个IP可以由多个用户共享。cookie可能是一个可行的选项,但cookie可能会过期或被客户端修改 在你的例子中,如果cookie被修改过,这似乎不是什么大问题,所以我建议在这种情况下使用cookie。 加载页面时,检查是否有cookie,如果没有,则创建一个cookie并向视图添加+1。如果已设置,则不要执行+1 将Cookie过期日期设置为您想要的任何日期,如果您想要的话,可以设置为星期或天,并且它将在该时间之后过期。过期后,它将再次成为唯一用户
编辑:
我觉得在这里添加此通知可能是个好主意…
由于大约在2016年底,IP地址(静态或动态)在欧盟被视为个人数据。
这意味着您只允许存储一个IP地址,并且有一个很好的理由(我不确定跟踪视图是否是一个很好的理由)。因此,如果您打算存储访问者的IP地址,我建议您使用无法逆转的算法对其进行哈希或加密,以确保您没有违反任何法律(特别是在实施GDPR法律之后)。这是一个很好的教程,它正是您所需要的。 (来源:) 注册并显示在线用户和访问者 使用MySQL表统计在线用户和访问者 在本教程中,您可以学习如何注册、计数以及在网页中显示在线用户和访问者的数量。 其原理是:每个用户/访问者都在文本文件或数据库中注册。每次访问网站的某个页面时,php脚本都会删除超过某个时间(例如2分钟)的所有记录,添加当前用户/访问者,并获取要显示的记录数 您可以将在线用户和访问者存储在服务器上的文件或MySQL表中。 在这种情况下,我认为使用文本文件添加和读取记录要比将记录存储到MySQL表中更快,因为MySQL表需要更多的请求 首先介绍了在服务器上记录文本文件的方法,而不是使用MySQL表的方法 要下载包含本教程中介绍的脚本的文件,请单击-> •这两个脚本都可以包含在“.php”文件(使用
include()
)或“.html”文件(使用
)中,如本页底部的示例所示;但是服务器必须运行PHP
将在线用户和访问者存储在文本文件中
要在使用PHP的服务器上的文件中添加记录,必须对该文件设置CHMOD 0766(或CHMOD 0777)权限,以便PHP可以在其中写入数据
userson.txt
),并授予其CHMOD 0777
权限(在FTP应用程序中,右键单击该文件,选择属性,然后选择读取
,写入
,以及执行
选项)usersontxt.PHP
),然后将此PHP文件复制到与userson.txt
相同的目录中<?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
?>
userson
表中插入、删除和选择数据(有关代码的解释,请参阅脚本中的注释)- 将下面的代码添加到另一个php文件中(名为
): 在这两个文件中,您必须在变量中添加连接到MySQL数据库的个人数据:usersmysql.php
、$host
、$user
和$pass
$dbname
<?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();
?>
<?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
?>
这两个脚本(将数据存储在服务器上的文本文件中,或存储到MySQL表中)将显示如下结果:
在线:5
参观人数:3人
用户:2
- 马普洛
- 马吕斯
时间()
(表示现在),并增加一个视图
否则,什么也不做
FYI:用户IP存储在$\u服务器['REMOTE\u ADDR']
变量中我编辑了“最佳答案”代码,但发现缺少一个有用的东西。如果用户正在使用代理,或者服务器安装了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
来自talkerscode官方教程的代码如果您有任何问题可能基于IP地址,您可以随时查看@mihai我觉得如果我读了代码,我理解的困难就会少一些。如果你不这么想,我告诉过你,你可以链接到一些教程。如果你有耐心
$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
$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' ");
}