具有活动记录的登录限制功能

时间:2012-10-29 00:28:16

标签: codeigniter activerecord login throttling

我有一个函数,我发现写的是使用PDO,我修改它以使用codeigniters活动记录db类。当我将代码放在如下函数中时,一切都有效:

    function login_attempt_count() {

      $seconds = 10;
         // First we delete old attempts from the table 
      $oldest1 = strtotime(date('Y-m-d H:i:s').' - '.$seconds.' seconds');
      $oldest2 = date('Y-m-d H:i:s',$oldest1);
      $del_data = $oldest2;
      $this->db->where('when <', $del_data);
      $this->db->delete('Login_Attempts');
        // Next we insert this attempt into the table
      $data = array(
      'ip' => $_SERVER['REMOTE_ADDR'],
      'when' => date("Y-m-d H:i:s"));
      $this->db->insert('Login_Attempts', $data);

        // Finally we count the number of recent attempts from this ip address 
      $count = 'SELECT count(*) as number FROM Login_Attempts WHERE ip = ?';
      $num = $this->db->query($count, $_SERVER['REMOTE_ADDR']);
      if ($num->num_rows() > 0){
        foreach($num->result() as $attempt){
          $attempts = $attempt->number;
            return $attempts;
        }
      }
 }   

像这样使用它:

    $max_attempts = 3;

    if(login_attempt_count() <= $max_attempts) {
        echo 'login';
    }else{
        echo 'To many attempts';
    } 

或者这个:

 $a = login_attempt_count();

导致页面的其余部分无法加载。所以这表示错误。 再次,如果我在函数内使用函数内部的代码,它将按预期工作。

或者,如果我应该使用一种完全更好,更安全的方法,我愿意接受建议。谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我在回答我自己的问题。 ;)功能正常!但是,在视图中测试会导致错误吗?将函数放在我的模型中并在我的控制器中调用函数后效果很好。像这样使用它:

class Auth extends CI_Controller{

   function login(){

   $max_attempts = 3;
        if($this->auth_model->login_attempt_count() <= $max_attempts) {
          //Do something
        }else{
          //Something else
        } 
   }//End Function
}//End Class