PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 4.0.21
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v4.0.21
4.1.16 4.1.15 4.1.14 4.1.13 4.1.12 4.1.11 4.1.10 4.0.30 4.0.29 4.0.28 4.0.27 4.0.26 4.0.24 4.0.25 4.0.23 4.0.22 4.0.21 4.0.19 4.0.18 4.0.17 4.0.16 1.9.3 1.9.4 1.9.5 1.9.6 All 170 releases
searchpro / BerqWP / src / RateLimiter.php

RateLimiter.php in BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript 4.0.21, at BerqWP/src/RateLimiter.php

62 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace BerqWP;
4
5 class RateLimiter
6 {
7 private $limit;
8 private $timeWindow; // In seconds
9 private $storagePath;
10
11 public function __construct($limit, $timeWindow, $storagePath)
12 {
13 $this->limit = $limit;
14 $this->timeWindow = $timeWindow; // e.g. 60 seconds for 1 minute
15 $this->storagePath = rtrim($storagePath, '/') . '/';
16 }
17
18 public function isRateLimited($clientIdentifier)
19 {
20 if (!is_dir($this->storagePath)) {
21 mkdir($this->storagePath, 0755, true);
22 }
23
24 $filePath = $this->storagePath . md5($clientIdentifier) . '.json';
25
26 if (!file_exists($filePath)) {
27 // Create a new entry if it doesn't exist
28 $this->createLog($filePath);
29 return false; // Not rate limited
30 }
31
32 // Read the log file
33 $logData = json_decode(file_get_contents($filePath), true);
34 $currentTime = time();
35
36 if (!is_array($logData)) {
37 $logData = [];
38 }
39
40 // Remove old entries from the time window
41 $logData = array_filter($logData, function($timestamp) use ($currentTime) {
42 return ($currentTime - $timestamp) <= $this->timeWindow;
43 });
44
45 // Check if the limit is reached
46 if (count($logData) >= $this->limit) {
47 return true; // Rate limited
48 }
49
50 // Otherwise, add the new timestamp and update the log
51 $logData[] = $currentTime;
52 file_put_contents($filePath, json_encode($logData));
53 return false;
54 }
55
56 private function createLog($filePath)
57 {
58 $logData = [time()];
59 file_put_contents($filePath, json_encode($logData));
60 }
61 }
62