我想在我的网页中添加一个计数器来计算访问者的数量。 但我的问题是,当我刷新我的页面时,计数器增加1 ..我希望该计数器仅在具有另一个IP的新访问者到达我的网页时才会增加。 这是我的代码.. 抱歉我的英语不好
的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);
}
答案 0 :(得分:1)
由于不希望使用基于数据库的解决方案,您可以尝试以下基于文件的解决方案来计算唯一身份访问者。您已经在代码中使用了 counter.txt 文件。
我尝试使用您使用的相同文件。在我的情况下,我将IP地址存储在该文件中。我使用base64编码功能只是为了隐藏IP地址。将该文件保存在安全的地方总是好的。如果该文件丢失,则唯一的访问者IP将丢失。请参阅以下功能:
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
答案 1 :(得分:0)
变化:
if(isset($_SESSION['current_user']))
为:
if($_SERVER['REMOTE_ADDR'] == $_SESSION['current_user'])
而且,当然你不需要从文件中获取$ count,然后将相同的值写回文件......?如果$ _SERVER [&#39; REMOTE_ADDR&#39;]匹配SESSION [&#39; current_user&#39;]则不执行任何操作..
答案 2 :(得分:0)
尝试将用户IP存储在数据库中并检查唯一用户
<?php
session_start();
if (!$_SESSION['status']) {
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("ip_log", $connection);
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `database`.`table` (IP) VALUES ('$ip')");
mysql_close($connection);
$_SESSION['status'] = true;
}
&GT;
答案 3 :(得分:0)
最佳易用代码
尝试将用户IP存储在数据库中并检查唯一用户
$`servername` = "";
$username = "";
$password = "";
$`dbname` = "";
$`conn` = new `mysqli`($`servername`, $username, $password, $`dbname`);
if ($`conn`->connect_error) {
die("Connection failed: " . $`conn`->connect_error);
}
$address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$name = `gethostname`();
$re = "select * from visitor where name='$name'";
$call = `mysqli_fetch_array`($re);
$as = `mysqli_num_rows`($call);
if($as == 0){
$`sql` = "UPDATE visitor SET visits = visits+1 WHERE name = '$name'";
}else{
$`sql` = "INSERT INTO visitor(visits,name,address) VALUE(1,'$name','$address')";
}
$`conn`->query($`sql`);
$`sql` = "SELECT visits FROM visitor WHERE id = 1";
$result = $`conn`->query($`sql`);
if ($result->`num_rows` > 0) {
while($row = $result->fetch_assoc()) {
$visits = $row["visits"];
}
} else {
$visits = "";
//echo $visits;
}
`$conn`->close();