php code to block login of a user for 15 minutes after 3 failed attempts...


please

Lusiphur commented: Just a note, google is your friend, research before asking others to do your work for you :) +0

Dani AI

Generated

If you just need something that works, here is a drop‑in pattern that locks a username for 15 minutes after 3 bad tries within a 15‑minute window. It ties the counter to the account (not only the IP), uses generic errors to avoid user enumeration, and resets on success. Create table auth_throttle(subject PK UNIQUE, failed_count INT, last_failed_at DATETIME, locked_until DATETIME) and make subject values like user:123 or name:<sha256(username)> so even unknown usernames get throttled. This aligns with OWASP guidance on login throttling and generic error messages. OWASP Authentication Cheat Sheet

<?php
// $pdo is PDO; $username and $password come from POST (validated).
$u = $pdo->prepare('SELECT id, password_hash FROM users WHERE username=?'); 
$u->execute([$username]); 
$user = $u->fetch(PDO::FETCH_ASSOC);

$subject = $user ? 'user:'.$user['id'] : 'name:'.hash('sha256', strtolower($username));
$pdo->prepare('INSERT INTO auth_throttle(subject,failed_count,last_failed_at,locked_until)
VALUES (?,0,NULL,NULL) ON DUPLICATE KEY UPDATE subject=subject')->execute([$subject]);

$t = $pdo->prepare('SELECT failed_count,last_failed_at,locked_until FROM auth_throttle WHERE subject=?');
$t->execute([$subject]); 
$thr = $t->fetch(PDO::FETCH_ASSOC);

if (!empty($thr['locked_until']) && strtotime($thr['locked_until']) > time()) {
    exit('Invalid credentials. Try again later.');
}

$hash = $user ? $user['password_hash'] : password_hash('dummy', PASSWORD_DEFAULT); // precompute in config for speed
$ok = password_verify($password, $hash);

if ($ok && $user) {
    $pdo->prepare('UPDATE auth_throttle SET failed_count=0,last_failed_at=NULL,locked_until=NULL WHERE subject=?')
        ->execute([$subject]);
    // proceed with login
} else {
    $window = time() - 15*60;
    $failCount = (!empty($thr['last_failed_at']) && strtotime($thr['last_failed_at']) > $window) ? $thr['failed_count']+1 : 1;
    $lock = $failCount >= 3 ? date('Y-m-d H:i:s', time()+15*60) : null;
    $pdo->prepare('UPDATE auth_throttle SET failed_count=?, last_failed_at=NOW(), locked_until=? WHERE subject=?')
        ->execute([$failCount, $lock, $subject]);
    exit('Invalid credentials.');
}

Notes for and others: use password_hash/password_verify (Argon2id or bcrypt). PHP password_hash manual Consider wrapping the read/update in a transaction with SELECT ... FOR UPDATE to avoid race conditions; add a light IP throttle or CAPTCHA after a few failures to reduce credential stuffing; and keep messages generic. NIST recommends throttling rather than permanent lockout and allows shorter, increasing delays to balance usability. NIST SP 800-63B (rate limiting)

Recommended Answers

All 7 Replies

for 'google is your friend' I always like "Let Me Google That For You' and 'Just f_ing Google It' to bring a little levity to the reply

its not urgent to ME no matter how many capitals there are

commented: My sentiments exactly! +1

[start_rant]
Maybe it's just me but we seem to be getting a lot of posts from newbies (more than normal) who post vague general questions or dump a whole bunch of code that isn't working and expect someone who knows what they are doing to spend a bunch of time doing something that they may have been too lazy to do for themselves. You don't need to be a php expert to post a question or a problem (probably quite the opposite most of the time). I think that we should expect some effort on their part first to do some research, some testing / debugging and provide a decent statement of the problem / question before they get any help. In many cases, you can do the work to get them an answer and you don't even get a response much less a thank you. Maybe what the internet needs is a global rating of every person for intelligence and as a decent human being. This would follow you around everywhere you go so everyone would know what they are dealing with. Sort of like the DaniWeb + or - ratings for individual posts but on steroids. I am kidding (mostly) but it seems that there are quite a few people who would deserve to be blacklisted on one or both counts.
[end_rant]

commented: agreed, very well said ^_^ +1
commented: My sentiments exactly! +1

This was so URGENT he didn't even have time to reply back. ;>

this very good way to do that

I am trying configure such as well, I came across this link http://www.daniweb.com/web-development/php/threads/324747/login-form-help which the syntax in the code seems to be wrong first, no biggie...yet I am unable to get anything like this to work...this one just redirects to header and tracks with column 'attempts' or is at least supposed to. However, a timeout would be good too. My current script just states invalid and then link for retry. I have been stuck on this for a while and not sure if I must get out of outher routine in that to make the other enforce in php and I guess timed prevention would need to get ip and put in database and concate to some script to prevent login or something...anyway...hope this is clear enough.

I'm so sorry for late reply. I'm out station to other place so..Please forgive me.

pritaeas, your solution help me a lots! Thanks =D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.