2016-04-27 86 views
1

我必须限制登录,如果大规模失败尝试进入,我想阻止所有IP。如何使用以下代码实现该目标?如果下面的代码不够好,请告知关于此事的好教程。登录限制并阻止所有IP地址

<?php 
$throttle = array(1 => 1, 10 => 2, 1000 => 'captcha'); 
$getfailedq = 'SELECT MAX(attempted) AS attempted FROM failed_logins'; 
$getfailed = $muc->prepare($getfailedq); 
$getfailed->execute(); 
if ($getfailed->rowCount() > 0) { 
    $row = $getfailed->fetch(PDO::FETCH_ASSOC); 
    $latest_attempt = (int) date('U', strtotime($row['attempted'])); 
    $getfailedq = 'SELECT Count(*) AS failed FROM failed_logins WHERE attempted > Date_sub(Now(), INTERVAL 15 minute)'; 
    $getfailed = $muc->prepare($getfailedq); 
    $getfailed->execute(); 
    if ($getfailed->rowCount() > 0) { 
     $row = $getfailed->fetch(PDO::FETCH_ASSOC); 
     $failed_attempts = (int) $row['failed']; 
     krsort($throttle); 
     foreach ($throttle as $attempts => $delay) { 
      if ($failed_attempts > $attempts) { 
       if (is_numeric($delay)) { 
        $remaining_delay = time() - $latest_attempt + $delay; 
        echo 'You must wait ' . $remaining_delay . ' seconds before your next login attempt'; 
       } else { 
        echo "captcha"; 
       } 
       break; 
      } 
     }   
    } 
} 
?> 
+0

为什么你绑定参数,当你的查询都没有任何参数在他们的? –

+0

这是一个很好的问题,谢谢,修正了查询 – Serjio

+2

'if($ getfailed-> rowCount()> 0){'这将永远是真实的,所以你的第一个查询是毫无意义的 – cmorrissey

回答

3

这基本上是伪代码,根据你的例子。您可以将ip字段添加到failed_logins表中,并创建一个名为blocked_logins的新表。

<?php 

// get users IP address 
$ip = $_SERVER['REMOTE_ADDR']; 

// find out if user has already been blocked 
$getblockedq = 'SELECT ip FROM blocked_logins WHERE ip = :ip'; 
$getblocked = $muc->prepare($getblockedq); 
$getblocked->execute(array(':ip' => $ip)); 
$total = $getblocked->fetchColumn(); 

if ($total > 0) { 
    // user is blocked, do not proceed 
} 

// find number of failed logins within past 15 mins 
$getfailedq = 'SELECT Count(*) AS failed FROM failed_logins WHERE ip = :ip AND attempted > Date_sub(Now(), INTERVAL 15 minute)'; 
$getfailed = $muc->prepare($getfailedq); 
$getfailed->execute(array(':ip' => $ip)); 
$total = $getfailed->fetchColumn(); 

if ($total <= 2) { 
    // looks good, attempt to login 
} elseif ($total <= 10) { 
    // you must wait x seconds... 
} elseif ($total <= 1000) { 
    // display captcha 
} else { 
    // block user 
} 

这应该至少让你开始正确的方向。

+0

谢谢,但我得到这个错误 致命的错误:调用未定义的方法PDO :: fetchColumn() – Serjio

+0

@Serjio抱歉,这只是用于逻辑,而不是语法的伪代码。试试这样:'$ getblocked-> fetchColumn();'我更新了我的示例。 –