Guest User

Untitled

a guest
Feb 14th, 2025
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. <?php
  2. // Connect to Redis
  3. $redis = new Redis();
  4. $redis->connect('127.0.0.1', 6379);
  5.  
  6. // Get the client IP
  7. $clientIp = $_SERVER['REMOTE_ADDR'];
  8.  
  9. // Normalize IPv6 addresses to /64 (for IPv6, split by ':' and join the first 4 parts)
  10. if (strpos($clientIp, ':') !== false) {
  11. $parts = explode(':', $clientIp);
  12. // Ensure we have at least 4 parts; adjust if needed based on your IPv6 formatting
  13. $clientIp = implode(':', array_slice($parts, 0, 4));
  14. }
  15.  
  16. $limit = 100; // Maximum allowed requests
  17. $timeWindow = 60; // Time window in seconds
  18.  
  19. $key = "rate_limit:{$clientIp}";
  20.  
  21. // Atomically increment the counter
  22. $count = $redis->incr($key);
  23. if ($count == 1) {
  24. // Set the expiration for the first hit in the window
  25. $redis->expire($key, $timeWindow);
  26. }
  27.  
  28. // Check if the limit has been exceeded
  29. if ($count > $limit) {
  30. header("HTTP/1.1 429 Too Many Requests");
  31. echo "Too many requests. Please try again later.";
  32. exit;
  33. }
  34.  
  35. // Proceed with the rest of your application logic...
  36. ?>
  37.  
Advertisement
Add Comment
Please, Sign In to add comment