deny foreach ($ips as $ip) { $ok = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ); if ($ok === false) return false; } return true; } } if (!function_exists('proxy_rate_limit')) { /** * Returns true if the request is allowed. Uses a tiny file per * (endpoint, client IP) holding recent unix timestamps. */ function proxy_rate_limit(string $endpoint, int $max = 30, int $windowSec = 60): bool { $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; $key = preg_replace('/[^A-Za-z0-9._-]/', '_', $endpoint . '_' . $ip); $dir = sys_get_temp_dir() . '/sillylaird_ratelimit'; if (!is_dir($dir)) @mkdir($dir, 0700, true); $file = $dir . '/' . $key; $now = time(); $cutoff = $now - $windowSec; $fp = @fopen($file, 'c+'); if (!$fp) return true; // fail-open: don't block legit traffic on disk error try { flock($fp, LOCK_EX); $data = stream_get_contents($fp); $stamps = $data === '' ? [] : array_map('intval', explode("\n", trim($data))); $stamps = array_values(array_filter($stamps, fn($t) => $t >= $cutoff)); if (count($stamps) >= $max) { return false; } $stamps[] = $now; ftruncate($fp, 0); rewind($fp); fwrite($fp, implode("\n", $stamps)); return true; } finally { flock($fp, LOCK_UN); fclose($fp); } } }