展会信息港展会大全

利用Memcache来限制访问次数过快
来源:互联网   发布日期:2016-03-02 15:13:16   浏览:2233次  

导读:?php $limit = 50; $seconds = 60; $block_for_seconds = 300; $status = ‘OK’; $memcache = new Memcache; $memcache-connect(‘localhost’, 11211); $ip = $_SERVER['REMOTE_ADDR']; $r = $memcache-get($ip, array(‘c’, ‘t’)); $c = 1; // count $...

<?php

$limit = 50;

$seconds = 60;

$block_for_seconds = 300;

$status = ‘OK’;

$memcache = new Memcache;

$memcache->connect(‘localhost’, 11211);

$ip = $_SERVER['REMOTE_ADDR'];

$r = $memcache->get($ip, array(‘c’, ‘t’));

$c = 1; // count

$init_time = time();

if($r) {

$s = $r[3]; // status

$c = $r[0]+1;

$init_time = $r[1];

if($s == ‘TOO_MANY_REQUESTS’) {

$d = time()-$r[1]; // time since block

if($block_for_seconds-$d > 0) { // still blocked

die(‘Flood detected!! You are going to wait ‘.($block_for_seconds-$d).’ and try again.’);

} else { // block is over

$status = ‘OK’;

$init_time = time();

$c = 0;

}

}

$new_time = time();

if($c > $limit) { // check if happened within a minute

$time_elapsed = $new_time – $init_time;

if($time_elapsed < $seconds) {

$status = ‘TOO_MANY_REQUESTS’;

}

print “time elapsed: $time_elapsed, count:$c”;

$c = 0;

$init_time = time();

}

}

print_r($r);

$memcache->set($ip, array($c, $init_time, $new_time, $status) );

?>

赞助本站

人工智能实验室

相关热词: 开发 编程 android

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港