A simple rate limiter in php and memcached
I'm trying to make a simple rate limiter, based on the comments from here开发者_运维技巧:
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));
Why does the above code return bool(false)?
this might not be appropriate but I believe a rate limiter should be as bare as possible. Below I have tried to a simple session-based limiter.
<?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();
}
Read add()
method syntax:
bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )
you have
$key = $name . $user_session
$var = 0
$flag = $time
so, before $time write null (flag).
$memcache->add($name . $user_session, 0, null, $time);
And I think method set
will be more useful here.
精彩评论