Jinsi ya Kufuatilia Login Attempts na Security
Kuzuia brute-force attacks (kujaribu password mara nyingi).
Kufunga account baada ya attempts nyingi zisizo sahihi.
Kutoa alert au lockout kwa user na admin.
Mfumo huu unaweza kutumia:
Database tracking – ku-record attempts per user/email.
Session tracking – kufuatilia attempts kwa current session (simple).
Combination – best practice kwa production.
⚙️ 2. Database Setup ya Tracking Attempts
CREATE TABLE login_attempts (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) NOT NULL,
attempt_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
💡 Maelezo:
Kila failed login attempt inarekodiwa hapa.
Unaweza ku-check attempts za last X minutes.
🧩 3. Tracking Login Attempts kwa PHP
<?php
include 'config.php';
session_start();
$max_attempts = 5; // Max failed attempts
$lockout_time = 15; // Minutes
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$email = trim($_POST['email']);
$password = $_POST['password'];
// Check number of failed attempts in last 15 minutes
$stmt = $pdo->prepare("SELECT COUNT(*) AS attempts
FROM login_attempts
WHERE email=:email AND attempt_time > (NOW() - INTERVAL :lockout MINUTE)");
$stmt->execute(['email'=>$email, 'lockout'=>$lockout_time]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['attempts'] >= $max_attempts){
$error = "❌ Too many login attempts. Try again after $lockout_time minutes.";
} else {
// Check user credentials
$stmt = $pdo->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(['email'=>$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if($user && password_verify($password, $user['password'])){
// Login success
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// Optional: Delete previous failed attempts
$stmt = $pdo->prepare("DELETE FROM login_attempts WHERE email=:email");
$stmt->execute(['email'=>$email]);
header("Location: dashboard.php");
exit;
} else {
// Record failed attempt
$stmt = $pdo->prepare("INSERT INTO login_attempts (email) VALUES (:email)");
$stmt->execute(['email'=>$email]);
$error = "❌ Invalid email or password!";
}
}
}
?>
💡 Maelezo:
Kila failed login attempt inarekodiwa.
User anafungwa baada ya attempts nyingi ndani ya dakika fulani.
📝 4. Vidokezo vya Usalama Zaidi
Use HTTPS: Hakikisha data ya login inasafirishwa salama.
Account Lockout: Consider permanent lockout or alert admin after multiple attempts.
Captcha: Ongeza CAPTCHA baada ya failed attempts kadhaa.
Logging: Record IP addresses kwa audit logs.
Session Management: Logout user baada ya inactivity.
✅ 5. Hitimisho
Tracking login attempts ni sehemu muhimu ya web security.
Husaidia kuzuia brute-force attacks na kuimarisha user authentication.
Best practice: combine attempt tracking, CAPTCHA, HTTPS, password hashing.
🔗 Tembelea:
👉 https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, security, sessions, na authentication.