gpt4 book ai didi

php - 防止PHP脚本被淹没

转载 作者:行者123 更新时间:2023-12-02 05:23:24 25 4
gpt4 key购买 nike

我想防止我的脚本被淹没 - 如果用户按 F5,它每次都会执行脚本。

我想防止这种情况并允许每 2 秒执行一个脚本,有什么解决方案吗?

最佳答案

你可以使用 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 () );
}

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

一个。更好的 IP 地址检测(代理、Tor)

B.当前操作

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

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

编辑 1 - 改进版本

用法

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

echo "Welcome" ;

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

}

关于php - 防止PHP脚本被淹没,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10155339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com