重复请求检测示例-php
2025-01-22 本文已影响0人
码农工号9527
<?php
checkRepeatReq(['a' => 1, 'b' => 2, 'c' => 3]);
function checkRepeatReq(array $reqParams, string $prefix = '')
{
$url_path = Request::getPathInfo();
if (!$url_path || $url_path == 'favicon.ico') {
$url_path = '/';
}
$host = Request::domain();
if (is_array($reqParams)) {
$reqParams = http_build_query($reqParams);
}
$key = md5($host . $url_path . $reqParams);
if ($prefix) {
return $prefix . ':' . $key;
}
// 是否为重复请求
if (duplicateReq($key)) {
var_dump('重复请求');
die();
} else {
var_dump('正常请求');
die();
}
}
function duplicateReq(string $id, int $expire = 0): bool
{
$repeat = false;
// 创建Redis实例
$redis = new Redis();
// 连接Redis服务器,这里假设Redis服务器运行在本地,默认端口是6379
$redis->connect('127.0.0.1', 6379);
// 认证(如果设置了密码)
// $redis->auth('yourpassword');
if ($expire <= 0) {
$expire = rand(100, 600);
}
$key = 'sdkrrqq:' . $id;
try {
$c = $redis->exists($key);
if (!empty($c)) {
$repeat = true;
} else {
$redis->setEx($key, $expire, '1');
}
} catch (Exception $ex) {
}
return $repeat;
}
?>