AlexWebDevelop

IP-based login limiting: PHP

Mar 4th, 2021
1,249
136 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Initialize the variables. */
  2. $failedLogins = 0;
  3. $lastFailedTimestamp = 0;
  4.  
  5. /* Get the remote user's IP address. */
  6. $ip = $_SERVER['REMOTE_ADDR'];
  7.  
  8. /* Get the login attempts data from the database. */
  9. $query = 'SELECT *, UNIX_TIMESTAMP(last_failed_timestamp) AS last_failed_uts FROM login_attempts WHERE (ip_address = :ip)';
  10. $stmt = $pdo->prepare($query);
  11.  
  12. $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
  13. $stmt->execute();
  14. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  15.  
  16. if (is_array($row))
  17. {
  18.   /* If there is a row for this IP address, read the variables. */
  19.   $failedLogins = intval($row['failed_logins'], 10);
  20.   $lastFailedTimestamp = intval($row['last_failed_uts'], 10);
  21. }
  22. else
  23. {
  24.   /* If there is no row yet, insert a new one. */
  25.   $query = 'INSERT INTO login_attempts (ip_address, failed_logins, last_failed_timestamp) VALUES (:ip, 0, NOW())';
  26.   $stmt = $pdo->prepare($query);
  27.   $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
  28.   $stmt->execute();
  29. }
  30.  
  31. /* Check if the failed logins counter must be reset. */
  32. if ((time() - $lastFailedTimestamp) > 3600)
  33. {
  34.   if ($failedLogins > 0)
  35.   {
  36.     /* Reset the counter and update the database. */
  37.     $failedLogins = 0;
  38.    
  39.     $query = 'UPDATE login_attempts SET failed_logins = 0 WHERE ip_address = :ip';
  40.     $stmt = $pdo->prepare($query);
  41.     $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
  42.     $stmt->execute();
  43.   }
  44. }
  45.  
  46. /* Check if there have been too many failed login attempts in the last hour. */
  47. if ($failedLogins > 30)
  48. {
  49.   echo 'Authentication failed.';
  50.   die();
  51. }
  52.  
  53. /* Continue with the user authentication... */
  54. $login = login($username, $password);
  55.  
  56. if (!$login)
  57. {
  58.   /* Login attempt failed: increment the failed logins counter. */
  59.   $failedLogins++;
  60.  
  61.   /* Update the database. */
  62.   $query = 'UPDATE login_attempts SET failed_logins = :logins WHERE ip_address = :ip';
  63.   $stmt = $pdo->prepare($query);
  64.  
  65.   $stmt->bindParam(':logins', $failedLogins, PDO::PARAM_INT);
  66.   $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
  67.   $stmt->execute();
  68. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×