我正在尝试在php中建立一个访客计数器。...
我不知道每天如何重新计数或重置计数器,因为可用的计数器仅计数一次
我的代码现在看起来像这样:
不确定该代码是否有效,但需要一些想法或建议。 谢谢
<?php
date_default_timezone_set("Asia/Kuala_Lumpur");//grab timezone
$now = date("H:i");
echo $now;
echo "<br>";
if($now == "00:00"){//when the clock is 00:00 count will be 0 again
$count = 0;
}
?>
<?php
session_start();
if(!isset($_SESSION['counter'])) { // It's the first visit in this session
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "Could not open the file" ;
}
else {
$counter = ( int ) fread ($handle,20) ;
fclose ($handle) ;
$counter++ ;
echo" <p> Visitor Count: ". $counter . " </p> " ;
$handle = fopen("counter.txt", "w" ) ;
fwrite($handle,$counter) ;
fclose ($handle) ;
$_SESSION['counter'] = $counter;
}
} else { // It's not the first time, do not update the counter but show the total hits stored in session
$counter = $_SESSION['counter'];
echo" <p> Visitor Count: ". $counter . " </p> " ;
}
?>
我的目标是每天显示访客人数。 p / s:一些代码来自stackoverflow。
答案 0 :(得分:0)
只有在服务器时间正好00:00有人访问您的网站时,您的代码才有可能正常工作。
您将需要cronjob或类似的名称,以在00:00重置.txt中的计数器,而与页面访问无关。
答案 1 :(得分:0)
您可以在文件中添加当天。检索数据时,如果文件中的日期不同,则为当天的首次访问,可以重置计数器:
date_default_timezone_set("Asia/Kuala_Lumpur");//grab timezone
$today = date("Y-m-d"); // get current date
session_start();
if(!isset($_SESSION['counter'])) { // It's the first visit in this session
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "Could not open the file" ;
}
else {
// retrieve the data
$line = fread($handle,20) ;
fclose ($handle) ;
$parts = explode(' ', $line);
$date = $parts[0]; // retrieve date in file
$counter = intval($parts[1]); // retrieve visit in file
// reset if first visit at a new day
if($date != $today)
{
$counter = 0 ;
}
// save the new date/counter data
$counter++ ;
echo" <p> Visitor Count: ". $counter . " </p> " ;
$handle = fopen("counter.txt", "w" ) ;
$newdata= $today . ' ' . $counter ; // put today + counter in the file
fwrite($handle,$newdata) ;
fclose ($handle) ;
$_SESSION['counter'] = $counter;
}
} else { // It's not the first time, do not update the counter but show the total hits stored in session
$counter = $_SESSION['counter'];
echo" <p> Visitor Count: ". $counter . " </p> " ;
}
答案 2 :(得分:0)
在stackoverflow上找到了它。
它的工作原理与我想要的完全一样。
谢谢您的帮助。
<?php
$filename = date("Ymd") . "_counter.txt";
$seenFilename = date("Ymd") . '_seen_ip.txt';
$ips = array();
if (file_exists($seenFilename))
{
$ips = file($seenFilename);
$ips = array_map('trim', $ips);
}
if(!in_array($_SERVER['REMOTE_ADDR'], $ips))
{
$visits = 0;
if (file_exists($filename)) {
$visits = file_get_contents($filename);
}
file_put_contents($filename, ++$visits);
$data = $_SERVER['REMOTE_ADDR'] . PHP_EOL;
$fp = fopen($seenFilename, 'a');
fwrite($fp, $data);
}
$fn = fopen($filename, "r");
$result = fgets($fn);
echo $result;
fclose($fn);
?>
p / s:一些代码来自stackoverflow。