rate_limit.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. // --- rate_limit.php (include at top of list_lookup.php) ---
  3. $store = __DIR__ . '/rate_limits.json';
  4. //$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
  5. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
  6. # If multiple IPs (comma separated), take the first (original client)
  7. if (strpos($ip, ',') !== false) {
  8. $ip = trim(explode(',', $ip)[0]);
  9. }
  10. $today = (new DateTime('now', new DateTimeZone('UTC')))->format('Y-m-d');
  11. $limit = 2;
  12. $all = [];
  13. if (file_exists($store)) {
  14. $json = file_get_contents($store);
  15. $all = json_decode($json, true) ?: [];
  16. }
  17. // reset other days automatically
  18. $count = $all[$ip][$today] ?? 0;
  19. if ($count >= $limit) {
  20. http_response_code(429);
  21. header('Content-Type: application/json');
  22. echo json_encode([
  23. 'ok' => false,
  24. 'error' => 'rate_limit_exceeded',
  25. 'message' => 'You have reached today’s free lookup limit.',
  26. 'limit' => $limit
  27. ]);
  28. exit;
  29. }
  30. // increment (do this just before returning OK later if you prefer “on success”)
  31. $all[$ip] = [$today => $count + 1];
  32. @file_put_contents($store, json_encode($all, JSON_PRETTY_PRINT));