有176人阅读过
一个简单的网页点击次数计数器php
发布于2025/08/14 更新于2025/08/14
[ 教程仅保证更新时有效,请自行测试。]
发布于2025/08/14 更新于2025/08/14
[ 教程仅保证更新时有效,请自行测试。]
[ 教程仅保证更新时有效,请自行测试。]
使用php写的一个简单的按钮点击次数计数器,提供计数和读数查询接口:
计数:?key={计数字段}&action=hit
读数:?key={计数字段}&action=get
下载php:
后端会以json格式记录对应字段的点击次数:
{
"xxx": 8,
"SPKServer": 2,
"MyTVAdmin": 6,
"ffmpeg7": 1,
"gitea": 1,
"TVBox": 3,
"transmission": 1,
"zblog": 2
}代码:
<?php
// 允许跨域
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=utf-8");
// 处理 OPTIONS 预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
$key = isset($_GET['key']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', $_GET['key']) : 'default';
$action = isset($_GET['action']) ? $_GET['action'] : 'get';
$file = __DIR__ . "/counts.json";
// 初始化文件
if (!file_exists($file)) {
file_put_contents($file, json_encode(new stdClass()));
}
$data = json_decode(file_get_contents($file), true);
if (!is_array($data)) {
$data = [];
}
if ($action === "hit") {
if (!isset($data[$key])) {
$data[$key] = 0;
}
$data[$key]++;
file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
$count = isset($data[$key]) ? $data[$key] : 0;
echo json_encode([
"key" => $key,
"value" => $count
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);此代码中有一个允许跨域的设置,其他程序中如果需要用到不同域名之间的调用,可以参考此设置:
// 允许跨域
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");文章对你有帮助吗?
- 一般[0]

- 很赞[0]

- 没用[0]

- 垃圾[0]

- 无语[0]


