Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Initialize the variables. */
- $failedLogins = 0;
- $lastFailedTimestamp = 0;
- /* Get the remote user's IP address. */
- $ip = $_SERVER['REMOTE_ADDR'];
- /* Get the login attempts data from the database. */
- $query = 'SELECT *, UNIX_TIMESTAMP(last_failed_timestamp) AS last_failed_uts FROM login_attempts WHERE (ip_address = :ip)';
- $stmt = $pdo->prepare($query);
- $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- if (is_array($row))
- {
- /* If there is a row for this IP address, read the variables. */
- $failedLogins = intval($row['failed_logins'], 10);
- $lastFailedTimestamp = intval($row['last_failed_uts'], 10);
- }
- else
- {
- /* If there is no row yet, insert a new one. */
- $query = 'INSERT INTO login_attempts (ip_address, failed_logins, last_failed_timestamp) VALUES (:ip, 0, NOW())';
- $stmt = $pdo->prepare($query);
- $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
- $stmt->execute();
- }
- /* Check if the failed logins counter must be reset. */
- if ((time() - $lastFailedTimestamp) > 3600)
- {
- if ($failedLogins > 0)
- {
- /* Reset the counter and update the database. */
- $failedLogins = 0;
- $query = 'UPDATE login_attempts SET failed_logins = 0 WHERE ip_address = :ip';
- $stmt = $pdo->prepare($query);
- $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
- $stmt->execute();
- }
- }
- /* Check if there have been too many failed login attempts in the last hour. */
- if ($failedLogins > 30)
- {
- echo 'Authentication failed.';
- die();
- }
- /* Continue with the user authentication... */
- $login = login($username, $password);
- if (!$login)
- {
- /* Login attempt failed: increment the failed logins counter. */
- $failedLogins++;
- /* Update the database. */
- $query = 'UPDATE login_attempts SET failed_logins = :logins WHERE ip_address = :ip';
- $stmt = $pdo->prepare($query);
- $stmt->bindParam(':logins', $failedLogins, PDO::PARAM_INT);
- $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
- $stmt->execute();
- }
RAW Paste Data