网站统计代码,部署本地服务器,自用版

最佳版 counter.php (带防刷 + 自动建目录)

<?php
// counter.php —— 今日访问量 + 累计访问量 + 防刷 + 自动创建目录版

// 设置时区
date_default_timezone_set(‘Asia/Shanghai’);

// 定义统计目录
$counter_dir = __DIR__ . ‘/counter/’;

// 如果目录不存在,自动创建
if (!is_dir($counter_dir)) {
mkdir($counter_dir, 0755, true);
}

// 文件路径
$counter_file = $counter_dir . ‘counter.txt’; // 统计数据
$ip_file = $counter_dir . ‘ip_log.txt’; // IP记录

// 初始化统计数据
$data = [
‘date’ => date(‘Y-m-d’),
‘today’ => 0,
‘total’ => 0
];

// 读取已有统计数据
if (file_exists($counter_file)) {
$file_data = json_decode(file_get_contents($counter_file), true);
if ($file_data && isset($file_data[‘date’]) && isset($file_data[‘today’]) && isset($file_data[‘total’])) {
if ($file_data[‘date’] == date(‘Y-m-d’)) {
$data[‘today’] = $file_data[‘today’];
}
$data[‘total’] = $file_data[‘total’];
}
}

// 获取访客IP
function getIP() {
if (!empty($_SERVER[‘HTTP_CLIENT_IP’])) {
return $_SERVER[‘HTTP_CLIENT_IP’];
}
if (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) {
return explode(‘,’, $_SERVER[‘HTTP_X_FORWARDED_FOR’])[0];
}
return $_SERVER[‘REMOTE_ADDR’] ?? ‘0.0.0.0’;
}

$ip = getIP();

// 防刷机制:5秒内同IP不重复计数
$ip_records = [];
if (file_exists($ip_file)) {
$content = file_get_contents($ip_file);
$ip_records = $content ? json_decode($content, true) : [];
}

// 清理超过5秒的记录
$now = time();
foreach ($ip_records as $logged_ip => $timestamp) {
if ($now – $timestamp > 5) {
unset($ip_records[$logged_ip]);
}
}

// 如果当前IP未在5秒内访问过,计数
if (!isset($ip_records[$ip])) {
$data[‘today’]++;
$data[‘total’]++;
$ip_records[$ip] = $now;
}

// 保存更新数据
file_put_contents($counter_file, json_encode($data));
file_put_contents($ip_file, json_encode($ip_records));

// 输出数据(JSON)
header(‘Content-Type: application/json’);
echo json_encode([
‘today’ => $data[‘today’],
‘total’ => $data[‘total’]
]);
?>

前端页面调用:

<div style=”text-align:center; font-size:14px; padding:10px;”>
今日访问人数:<span id=”today_count”>加载中…</span>,
累计访问人数:<span id=”total_count”>加载中…</span>
</div>

<script>
fetch(‘/counter.php’)
.then(response => response.json())
.then(data => {
document.getElementById(‘today_count’).innerText = data.today;
document.getElementById(‘total_count’).innerText = data.total;
})
.catch(error => {
console.error(‘统计加载失败’, error);
});
</script>

文件结构是:

/index.php
/footer.php
/counter.php
/counter/ ← 统计目录(自动创建)
counter.txt ← 记录今日访问和总访问
ip_log.txt ← 记录5秒内访问过的IP

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注