Skip to content

Instantly share code, notes, and snippets.

@jeremykendall
Created September 28, 2016 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremykendall/5d0e8284cb1fd86bf7bd44153352c226 to your computer and use it in GitHub Desktop.
Save jeremykendall/5d0e8284cb1fd86bf7bd44153352c226 to your computer and use it in GitHub Desktop.
<h1>Super Awesome Session-Based Rate Limiter</h1>
<?php
session_start();
$blocked = false;
$message = "You may pass.";
$now = new \DateTime();
$attempts = isset($_SESSION['attempts']) ? $_SESSION['attempts'] : [];
if (count($attempts) > 4) {
$oldest = new \DateTime($attempts[0]);
if ($oldest->modify('+1 minute') > $now) {
$blocked = true;
}
}
array_unshift($attempts, $now->format(\DateTime::ISO8601));
$attempts = array_slice($attempts, 0, 5);
$_SESSION['attempts'] = $attempts;
if ($blocked) {
$message = "YOU SHALL NOT PASS!";
}
?>
<p><strong><?= $message ?></strong></p>
<p>ATTEMPTS: <?= count($attempts); ?></p>
<ul>
<?php foreach ($attempts as $attempt): ?>
<li><?= $attempt; ?></li>
<?php endforeach; ?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment