程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 利用Memcache來限制訪問次數過快

利用Memcache來限制訪問次數過快

編輯:關於PHP編程

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

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved