防止PHP脚本被淹没

Luc*_*cas 2 php execution limit

我想阻止我的脚本被淹没 - 如果用户点击F5,它每次都在执行脚本.

我想阻止这种情况并允许每2秒执行一次脚本,有什么解决办法吗?

Bab*_*aba 16

你可以用memcache来做这个..

简单的演示脚本

$memcache = new Memcache ();
$memcache->connect ( 'localhost', 11211 );
$runtime = $memcache->get ( 'floodControl' );

if ((time () - $runtime) < 2) {
    die ( "Die! Die! Die!" );
} 

else {
    echo "Welcome";
    $memcache->set ( "floodControl", time () );
}
Run Code Online (Sandbox Code Playgroud)

这只是一个示例代码..还有其他需要考虑的事情

A.更好的IP地址检测(代理,Tor)

B.当前行动

C.每分钟最大执行次数等......

D.最大洪水等后禁止用户

编辑1 - 改进版本

用法

$flood = new FloodDetection();
$flood->check();

echo "Welcome" ;
Run Code Online (Sandbox Code Playgroud)

class FloodDetection {
    const HOST = "localhost";
    const PORT = 11211;
    private $memcache;
    private $ipAddress;

    private $timeLimitUser = array (
            "DEFAULT" => 2,
            "CHAT" => 3,
            "LOGIN" => 4 
    );
    private $timeLimitProcess = array (
            "DEFAULT" => 0.1,
            "CHAT" => 1.5,
            "LOGIN" => 0.1 
    );

    function __construct() {
        $this->memcache = new Memcache ();
        $this->memcache->connect ( self::HOST, self::PORT );
    }

    function addUserlimit($key, $time) {
        $this->timeLimitUser [$key] = $time;
    }

    function addProcesslimit($key, $time) {
        $this->timeLimitProcess [$key] = $time;
    }

    public function quickIP() {
        return (empty ( $_SERVER ['HTTP_CLIENT_IP'] ) ? (empty ( $_SERVER ['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER ['REMOTE_ADDR'] : $_SERVER ['HTTP_X_FORWARDED_FOR']) : $_SERVER ['HTTP_CLIENT_IP']);
    }

    public function check($action = "DEFAULT") {
        $ip = $this->quickIP ();
        $ipKey = "flood" . $action . sha1 ( $ip );

        $runtime = $this->memcache->get ( 'floodControl' );
        $iptime = $this->memcache->get ( $ipKey );

        $limitUser = isset ( $this->timeLimitUser [$action] ) ? $this->timeLimitUser [$action] : $this->timeLimitUser ['DEFAULT'];
        $limitProcess = isset ( $this->timeLimitProcess [$action] ) ? $this->timeLimitProcess [$action] : $this->timeLimitProcess ['DEFAULT'];

        if ((microtime ( true ) - $iptime) < $limitUser) {
            print ("Die! Die! Die! $ip") ;
            exit ();
        }

        // Limit All request
        if ((microtime ( true ) - $runtime) < $limitProcess) {
            print ("All of you Die! Die! Die! $ip") ;
            exit ();
        }

        $this->memcache->set ( "floodControl", microtime ( true ) );
        $this->memcache->set ( $ipKey, microtime ( true ) );
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 单例对静态类或实例对象没有任何好处.他们只是施加约束,并且在项目的后期阶段出现问题.难以测试,难以维护代码(紧密耦合等等等等等等).[阅读所有相关内容](http://programmers.stackexchange.com/questions/40373/so-singletons-are-bad-then-what) (2认同)