php和memcached中的一个简单速率限制器


A simple rate limiter in php and memcached

我想做一个简单的速率限制器,基于这里的评论:

function set_session_rate_limit($memcache, $name, $user_session, $time)
{
   $memcache->add($name . $user_session, 0, $time);
   return $memcache->increment($name . $user_session);
}

set_session_rate_limit($memcache, 'login_fail_', $user_session, 300);
function get_session_rate_limit($memcache, $name, $user_session)
{
   return $memcache->get($name . $user_session);
}

var_dump(get_session_rate_limit($memcache, 'login_fail_', $user_session));

为什么上面的代码返回bool(false)?

这可能不合适,但我认为速率限制器应该尽可能简单。下面我尝试了一个简单的基于会话的限制器。

<?php
    session_start();
    const cap = 3;//Max http requests a host can make
    const period = 5;//the period in which it limits,60 means 1 minuts
    $stamp_init = date("Y-m-d H:i:s");
    if( !isset( $_SESSION['FIRST_REQUEST_TIME'] ) ){
            $_SESSION['FIRST_REQUEST_TIME'] = $stamp_init;
    }
    $first_request_time = $_SESSION['FIRST_REQUEST_TIME'];
    $stamp_expire = date( "Y-m-d H:i:s", strtotime( $first_request_time )+( period ) );
    if( !isset( $_SESSION['REQ_COUNT'] ) ){
            $_SESSION['REQ_COUNT'] = 0;
    }
    $req_count = $_SESSION['REQ_COUNT'];
    $req_count++;
    if( $stamp_init > $stamp_expire ){//Expired
            $req_count = 1;
            $first_request_time = $stamp_init;
    }
    $_SESSION['REQ_COUNT'] = $req_count;
    $_SESSION['FIRST_REQUEST_TIME'] = $first_request_time;
    header('X-RateLimit-Limit: '.cap);
    header('X-RateLimit-Remaining: ' . ( cap-$req_count ) );
    if( $req_count > cap){//Too many requests
            http_response_code( 429 );
            exit();
    }

读取add()方法语法:
bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )
你有
$key = $name。美元user_session
$var = 0
$flag = $time
因此,在$time之前写入null (flag)。
$memcache->add($name . $user_session, 0, null, $time);
我认为set方法在这里更有用。