Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Connect to Redis
- $redis = new Redis();
- $redis->connect('127.0.0.1', 6379);
- // Get the client IP
- $clientIp = $_SERVER['REMOTE_ADDR'];
- // Normalize IPv6 addresses to /64 (for IPv6, split by ':' and join the first 4 parts)
- if (strpos($clientIp, ':') !== false) {
- $parts = explode(':', $clientIp);
- // Ensure we have at least 4 parts; adjust if needed based on your IPv6 formatting
- $clientIp = implode(':', array_slice($parts, 0, 4));
- }
- $limit = 100; // Maximum allowed requests
- $timeWindow = 60; // Time window in seconds
- $key = "rate_limit:{$clientIp}";
- // Atomically increment the counter
- $count = $redis->incr($key);
- if ($count == 1) {
- // Set the expiration for the first hit in the window
- $redis->expire($key, $timeWindow);
- }
- // Check if the limit has been exceeded
- if ($count > $limit) {
- header("HTTP/1.1 429 Too Many Requests");
- echo "Too many requests. Please try again later.";
- exit;
- }
- // Proceed with the rest of your application logic...
- ?>
Advertisement
Add Comment
Please, Sign In to add comment