Created
September 28, 2016 14:43
-
-
Save jeremykendall/5d0e8284cb1fd86bf7bd44153352c226 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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