PHP code example of ahur-system / ai-rate-limiter
1. Go to this page and download the library: Download ahur-system/ai-rate-limiter library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ahur-system / ai-rate-limiter example snippets
hurSystem\AIRateLimiter\AIRateLimiter;
// Initialize Redis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Create rate limiter
$limiter = new AIRateLimiter($redis, [
'default_limit' => 100,
'default_window' => 3600, // 1 hour
'learning_enabled' => true,
'adaptive_throttling' => true
]);
// Check rate limit
$result = $limiter->check('user_123', 'api/v1/users', [
'user_agent' => 'MyApp/1.0',
'ip' => '192.168.1.100'
]);
if ($result->isAllowed()) {
echo "Request allowed! Remaining: " . $result->getRemainingRequests();
} else {
echo "Rate limited! Retry after: " . $result->getRetryDelay() . " seconds";
}
$result = $limiter->check('user_123', 'api/v1/users');
echo "Allowed: " . ($result->isAllowed() ? 'Yes' : 'No') . "\n";
echo "Remaining: " . $result->getRemainingRequests() . "\n";
echo "Reset time: " . $result->getResetDateTime()->format('Y-m-d H:i:s') . "\n";
$result = $limiter->check('api_key_456', 'api/v1/data');
// Set HTTP headers
foreach ($result->getHeaders() as $name => $value) {
header("$name: $value");
}
// Check if rate limited
if (!$result->isAllowed()) {
http_response_code(429);
echo json_encode([
'error' => 'Rate limit exceeded',
'retry_after' => $result->getRetryDelay()
]);
exit;
}
$result = $limiter->check('user_123', 'api/v1/users');
$stats = $result->getStats();
echo "Current usage: " . $stats['current_usage'] . "\n";
echo "Pattern count: " . $stats['pattern_count'] . "\n";
echo "Usage trend: " . round($stats['trend'] * 100, 2) . "%\n";
echo "Burst factor: " . round($stats['burst_factor'], 2) . "\n";
// Available strategies
$strategies = $limiter->getStrategyDescriptions();
foreach ($strategies as $name => $description) {
echo "$name: $description\n";
}
// Use different strategies
$limiter = new AIRateLimiter($redis, [
'retry_strategy' => 'exponential' // Default: exponential backoff
]);
$limiter = new AIRateLimiter($redis, [
'retry_strategy' => 'linear' // Linear increase
]);
$limiter = new AIRateLimiter($redis, [
'retry_strategy' => 'jitter' // Exponential with random jitter
]);
$limiter = new AIRateLimiter($redis, [
'retry_strategy' => 'fixed' // Fixed delay
]);
$limiter = new AIRateLimiter($redis, [
'retry_strategy' => 'adaptive' // Pattern-based adaptive delay
]);
// Reset limits for a specific user and endpoint
$limiter->reset('user_123', 'api/v1/users');
bash
php examples/basic_usage.php