I wrote a small PHP with SQLite script which stores the IP with counter, it works fine with one problem, If I enter the correct password 4th time the counter becomes 4 and I get the error to enter my captcha. All the other times, 1-3 and 5 and above count it just works fine. What am I doing wrong with the logic.
Attaching the zip file with code.
https://drive.google.com/file/d/0B_Wnu0b7d6J-YlVmcWRmbjRuY3M/edit?usp=sharing
Forgot to add the code
<?php
session_start();
$IPaddress = $_SERVER["REMOTE_ADDR"];
$mainpage = "main.php";
$dblogin = new PDO("sqlite:LoginAttempts.db");
$CounterCheck = $dblogin->query("SELECT IP, Counter FROM LoginAttempts WHERE IP = '$IPaddress'");
$fields = $CounterCheck->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['submit']))
{
$error = 0;
$showcaptcha = 0;
$captchaerror = 0;
if (isset($_POST['username']))
{
$username = $_POST['username'];
}
if (isset($_POST['password']))
{
$password = $_POST['password'];
}
if (isset($_POST['imagetext']))
{
$imagetext = $_POST['imagetext'];
}
if(empty($username)) {
$username = 1;
}
if(empty($password)) {
$password = 1;
}
if($fields['Counter'] < 3)
{
if($username == "admin" && $password == "admin")
{
$_SESSION['logedin'] = 'success';
// Redirect to the page
header("Location: $mainpage");
$dblogin->query("UPDATE LoginAttempts SET Counter = '0' WHERE IP = '$IPaddress'");
exit();
}
else
{
$error == 1;
$errormessage = 'Invalid Username or Password';
$UpdateAttempt = $dblogin->query("UPDATE LoginAttempts SET Counter = Counter + 1 WHERE IP = '$IPaddress'");
$Updatecount = $UpdateAttempt->rowCount();
if ($Updatecount == 0)
{
$dblogin->exec("INSERT INTO LoginAttempts (IP, Counter) VALUES('$IPaddress', '1')");
}
}
}
if($fields['Counter'] >= 3)
{
// $showcaptcha = 1;
if(empty($imagetext)) {
$error = 1;
$captchaerror = 1;
} else {
include "captcha/securimage.php";
$img = new Securimage();
$valid = $img->check($imagetext);
if(!$valid) {
$errormessagecaptcha = "Invalid Captcha";
$captchaerror = 1;
}
}
if($captchaerror == 1)
{
$error == 1;
$errormessagecaptcha = 'Invalid Captcha';
$UpdateAttempt = $dblogin->query("UPDATE LoginAttempts SET Counter = Counter + 1 WHERE IP = '$IPaddress'");
$Updatecount = $UpdateAttempt->rowCount();
if ($Updatecount == 0)
{
$dblogin->exec("INSERT INTO LoginAttempts (IP, Counter) VALUES('$IPaddress', '1')");
}
}
else if($username == "admin" && $password == "admin" && $captchaerror == 0)
{
$_SESSION['logedin'] = 'success';
// Redirect to the page
header("Location: $mainpage");
$dblogin->query("UPDATE LoginAttempts SET Counter = '0' WHERE IP = '$IPaddress'");
exit();
}
else
{
$error == 1;
$errormessage = 'Invalid Username or Password';
$UpdateAttempt = $dblogin->query("UPDATE LoginAttempts SET Counter = Counter + 1 WHERE IP = '$IPaddress'");
$Updatecount = $UpdateAttempt->rowCount();
if ($Updatecount == 0)
{
$dblogin->exec("INSERT INTO LoginAttempts (IP, Counter) VALUES('$IPaddress', '1')");
}
}
}
}
?>