尝试限制登录尝试但查询不返回结果

时间:2016-08-03 21:09:25

标签: php mysqli

我使用以下代码将用户锁定为每5分钟SECURITY_FAIL_300次尝试的限制或每5秒SECURITY_FAIL_5次尝试。代码成功地阻止用户进行多次尝试(其他代码在尝试失败时添加条目)。但是,$ timeLimit值始终返回0.

如果我在php my admin

中尝试,查询将返回整数值

数据库表只包含2个coloumns。 ip是varchar(255),time是时间戳。

    $ip=$_SERVER['REMOTE_ADDR'];

    //setup queries
    $query="select TIME_TO_SEC(TIMEDIFF(NOW(),`time`)) from `accessattempts` where `ip`=? AND `time` >= DATE_SUB(NOW(),INTERVAL ? SECOND) ORDER BY `time` ASC";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("si",$ip,$limit);
    $stmt->bind_result($timeLeft);

    //see if gone past attemp limits
    $limitsTime=array(300,5);
    $limitsQuantity=array(SECURITY_FAIL_300,SECURITY_FAIL_5);
    $maxRemaining=0;
    for ($i=0;$i<2;$i++) {
        //what limits are we looking for
        $limit=$limitsTime[$i];
        $max=$limitsQuantity[$i];

        //look up how many times they tried
        $stmt->execute();
        $result = $stmt->get_result();
        $num_rows = $result->num_rows;
        if ($num_rows>$max) {
            //get number of seconds left
            $result->fetch_assoc();
            $remaining=$limit-$timeLeft;

            //see if it is more then other timeouts
            if ($remaining>$maxRemaining) $maxRemaining=$remaining;
        }
    }
    if ($maxRemaining>0) {
        echo json_encode(array(
            'success'   => false,
            'reason'    => 'To many attempts.  Locked out for: ' . $maxRemaining . ' seconds'
        ));die();   
    }
    $stmt->close();

1 个答案:

答案 0 :(得分:0)

你的ip是varchar所以你应该使用&#39; like&#39;而不是&#39; =&#39;。尝试: &#34;从timeaccessattempts选择TIME_TO_SEC(TIMEDIFF(现在(),ip))? AND time&gt; = DATE_SUB(NOW(),INTERVAL?SECOND)ORDER BY time ASC&#34;