PHP 防止恶意用户快速刷新页面

时间:2021-09-05 17:00:31
<?php
/**
 * 防止快速刷新
 *
 */
session_start(); 
header("Content-type:text/html;charset=utf-8");
error_reporting(E_ALL^E_NOTICE); 
// 参数: N秒内刷新M次,就禁止访问! 并且关小黑屋X秒!
$seconds = 3; //时间段[秒]
$refresh = 20; //刷新次数
$disdeny = 10; // 放开限制的时间: 30秒后

$sid = session_id();
if( !$_SESSION['denyvisitor'] ){
    $_SESSION['denyvisitor']=array();
}
if( in_array($sid,$_SESSION['denyvisitor']) && ( time()-$_SESSION['denytimestamp'][$sid]<$disdeny ) ){
    $alsotime = $disdeny - ( time()-$_SESSION['denytimestamp'][$sid] );
    exit( "您被关到小黑屋了! <span style='color:#f00;font-size:22px;'>{$alsotime}</span> 秒后可获*!" );
}
empty($_SERVER['HTTP_VIA']) or exit('Access Denied'); //代理IP直接退出

//设置监控变量
$cur_time = time();
if(isset($_SESSION['last_time'])){
    $_SESSION['refresh_times'] += 1;
}else{
    $_SESSION['refresh_times'] = 1;
    $_SESSION['last_time'] = $cur_time;
}

//处理监控结果
if($cur_time - $_SESSION['last_time'] < $seconds){
    if($_SESSION['refresh_times'] >= $refresh){  
        if(!in_array($$sid,$_SESSION['denyvisitor'])){
            $_SESSION['denyvisitor'][] = $sid;
            $_SESSION['denytimestamp'][$sid] = time();
        }
    }
}else{
    $_SESSION['refresh_times'] = 0;
    $_SESSION['last_time'] = $cur_time;
}