-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRateLimiter.php
47 lines (37 loc) · 1.1 KB
/
RateLimiter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
namespace WpStaging\AbTesting;
if (!defined('ABSPATH')) {
exit;
}
class RateLimiter
{
private int $maxRequests = 10;
private int $timeFrame = 60; // 60 seconds
public function init()
{
add_action('init', [$this, 'startSession']);
}
public function startSession()
{
if (!session_id()) {
session_start();
}
$clientIp = $_SERVER['REMOTE_ADDR'];
if (!isset($_SESSION['rate_limit'][$clientIp])) {
$_SESSION['rate_limit'][$clientIp] = [];
}
// Clear old requests
$_SESSION['rate_limit'][$clientIp] = array_filter(
$_SESSION['rate_limit'][$clientIp],
function ($timestamp) {
return $timestamp >= time() - $this->timeFrame;
}
);
// Check if limit is exceeded
if (count($_SESSION['rate_limit'][$clientIp]) >= $this->maxRequests) {
wp_die('Rate limit exceeded. Please try again later.', 429);
}
// Record the current request timestamp
$_SESSION['rate_limit'][$clientIp][] = time();
}
}