重復(fù)請(qǐng)求檢測(cè)示例-php

<?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;
    }

    // 是否為重復(fù)請(qǐng)求
    if (duplicateReq($key)) {
        var_dump('重復(fù)請(qǐng)求');
        die();
    } else {
        var_dump('正常請(qǐng)求');
        die();
    }
}

function duplicateReq(string $id, int $expire = 0): bool
{
    $repeat = false;

    // 創(chuàng)建Redis實(shí)例
    $redis = new Redis();

    // 連接Redis服務(wù)器,這里假設(shè)Redis服務(wù)器運(yùn)行在本地,默認(rèn)端口是6379
    $redis->connect('127.0.0.1', 6379);

    // 認(rèn)證(如果設(shè)置了密碼)
    // $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;
}

?>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容