PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / trunk
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript vtrunk
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 / vendor-prefixed / src / RateLimiter.php

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

56 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;
9 // In seconds
10 private $storagePath;
11 public function __construct($limit, $timeWindow, $storagePath)
12 {
13 $this->limit = $limit;
14 $this->timeWindow = $timeWindow;
15 // e.g. 60 seconds for 1 minute
16 $this->storagePath = rtrim($storagePath, '/') . '/';
17 }
18 public function isRateLimited($clientIdentifier)
19 {
20 if (!is_dir($this->storagePath)) {
21 mkdir($this->storagePath, 0755, \true);
22 }
23 $filePath = $this->storagePath . md5($clientIdentifier) . '.json';
24 if (!file_exists($filePath)) {
25 // Create a new entry if it doesn't exist
26 $this->createLog($filePath);
27 return \false;
28 // Not rate limited
29 }
30 // Read the log file
31 $logData = json_decode(file_get_contents($filePath), \true);
32 $currentTime = time();
33 if (!is_array($logData)) {
34 $logData = [];
35 }
36 // Remove old entries from the time window
37 $logData = array_filter($logData, function ($timestamp) use ($currentTime) {
38 return $currentTime - $timestamp <= $this->timeWindow;
39 });
40 // Check if the limit is reached
41 if (count($logData) >= $this->limit) {
42 return \true;
43 // Rate limited
44 }
45 // Otherwise, add the new timestamp and update the log
46 $logData[] = $currentTime;
47 file_put_contents($filePath, json_encode($logData));
48 return \false;
49 }
50 private function createLog($filePath)
51 {
52 $logData = [time()];
53 file_put_contents($filePath, json_encode($logData));
54 }
55 }
56