2016-04-27 83 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();'我更新了我的示例。 –