帮我用php写一个带key的计次器api
以下是一个简单的PHP计次器API,它需要一个密钥来访问:
<?php
// Replace YOUR_SECRET_KEY with your own secret key
$secret_key = 'YOUR_SECRET_KEY';
// Get the request parameters
$counter_name = $_GET['counter_name'];
$counter_value = $_GET['counter_value'];
$api_key = $_GET['api_key'];
// Verify the API key
if ($api_key != $secret_key) {
echo 'Invalid API key';
exit;
}
// Load the counter value from a file
$counter_file = 'counters/' . $counter_name . '.txt';
if (file_exists($counter_file)) {
$current_value = file_get_contents($counter_file);
} else {
$current_value = 0;
}
// Update the counter value
$new_value = $current_value + $counter_value;
file_put_contents($counter_file, $new_value);
// Output the new counter value
echo 'New value for ' . $counter_name . ': ' . $new_value;
?>
使用方法:
- 将以上代码保存为一个PHP文件,例如count.php;
- 将YOUR_SECRET_KEY替换为您自己的密钥;
- 在服务器上创建一个名为counters的目录;
- 通过以下URL调用API:http://yourdomain.com/count.php?counter_name=your_counter_name&counter_value=1&api_key=YOUR_SECRET_KEY
其中,your_counter_name是您想要计数的名称,counter_value是要添加到计数器中的值,YOUR_SECRET_KEY是您之前设置的密钥。
API将返回一个字符串,显示计数器的新值。例如,如果您的计数器名为“visits”,并且它当前的值为10,通过调用http://yourdomain.com/count.php?counter_name=visits&counter_value=1&api_key=YOUR_SECRET_KEY将返回“New value for visits: 11”。
原文地址: https://www.cveoy.top/t/topic/ERa 著作权归作者所有。请勿转载和采集!