setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $debug[] = "Database connected"; } catch (PDOException $e) { $debug[] = "Database error: " . $e->getMessage(); die("Database connection error: " . $e->getMessage()); } $error = ''; $success = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING); $debug[] = "Login attempt for: " . $username; if ($username && $password) { try { $stmt = $db->prepare('SELECT id, password, is_blocked, login_attempts, last_attempt FROM users WHERE username = ?'); $stmt->execute([$username]); $user = $stmt->fetch(PDO::FETCH_ASSOC); $debug[] = "User found: " . ($user ? 'yes' : 'no'); if ($user) { if ($user['is_blocked']) { $error = 'Account is blocked'; $debug[] = "Account blocked"; } else if ($user['login_attempts'] >= 5 && strtotime($user['last_attempt']) > strtotime('-15 minutes')) { $error = 'Too many login attempts'; $debug[] = "Too many attempts"; } else if (password_verify($password, $user['password'])) { $stmt = $db->prepare('UPDATE users SET login_attempts = 0, last_attempt = NOW() WHERE id = ?'); $stmt->execute([$user['id']]); $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $username; $debug[] = "Login successful"; header('Location: index.php'); exit; } else { $stmt = $db->prepare('UPDATE users SET login_attempts = login_attempts + 1, last_attempt = NOW() WHERE id = ?'); $stmt->execute([$user['id']]); $error = 'Invalid password'; $debug[] = "Invalid password"; } } else { $error = 'User not found'; $debug[] = "User not found"; } } catch (PDOException $e) { $error = 'Server error'; $debug[] = "SQL Error: " . $e->getMessage(); $debug[] = "SQL State: " . $e->getCode(); } } } ?>