<?php
// anti_cc.php - 在所有需保護腳本頂部 require_once
session_start();
// 配置
$config = [
'window_sec' => 3, // 時間窗口(秒)
'max_requests' => 5, // 窗口內最大請求數
'ban_duration' => 300, // 觸發封禁時長(秒)
'whitelist_ips' => ['127.0.0.1', '::1'], // 白名單
'log_file' => __DIR__ . '/logs/cc_block.log',
];
// 代理 IP 直接拒絕(可選,視業務)
if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// 更嚴格:檢測知名代理頭
// error_log("Proxy access denied: {$_SERVER['REMOTE_ADDR']}");
// exit('Access Denied: Proxy not allowed');
}
$ip = $_SERVER['REMOTE_ADDR'];
if (in_array($ip, $config['whitelist_ips'], true)) return; // 白名單放行
$now = time();
$key = "cc_limit:$ip";
// 初始化/重置窗口
if (!isset($_SESSION[$key]['window_start']) || $now - $_SESSION[$key]['window_start'] >= $config['window_sec']) {
$_SESSION[$key] = ['window_start' => $now, 'count' => 0];
}
$_SESSION[$key]['count']++;
if ($_SESSION[$key]['count'] > $config['max_requests']) {
// 觸發封禁
$_SESSION['banned_until'] = $now + $config['ban_duration'];
error_log(sprintf("[%s] CC Block: IP=%s Count=%d UA=%s\n", date('c'), $ip, $_SESSION[$key]['count'], $_SERVER['HTTP_USER_AGENT'] ?? ''), 3, $config['log_file']);
// 返回 429 Too Many Requests
http_response_code(429);
header('Content-Type: text/plain; charset=utf-8');
exit("請求過於頻繁,請 {$config['ban_duration']} 秒後重試。");
}
// 可選:將剩餘配額傳給前端
header('X-RateLimit-Limit: ' . $config['max_requests']);
header('X-RateLimit-Remaining: ' . max(0, $config['max_requests'] - $_SESSION[$key]['count']));
header('X-RateLimit-Reset: ' . ($_SESSION[$key]['window_start'] + $config['window_sec']));
<?php
// 依賴 predis/predis 或 phpredis 擴展
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
function checkRateLimit(Redis $redis, string $key, int $limit, int $windowSec): bool {
$now = microtime(true);
$windowStart = $now - $windowSec;
$pipe = $redis->pipeline();
// 移除過期記錄
$pipe->zRemRangeByScore($key, 0, $windowStart);
// 當前計數
$pipe->zCard($key);
// 添加本次請求
$pipe->zAdd($key, $now, "$now:" . uniqid('', true));
// 設置過期時間(窗口結束後自動清理)
$pipe->expire($key, $windowSec + 1);
$results = $pipe->execute();
$currentCount = $results[1];
return $currentCount < $limit;
}
// 使用
$ip = $_SERVER['REMOTE_ADDR'];
$limitKey = "ratelimit:api:$ip";
if (!checkRateLimit($redis, $limitKey, 100, 60)) { // 100 req/min
http_response_code(429);
exit(json_encode(['error' => 'Rate limit exceeded', 'retry_after' => 60]));
}
| 層級 | 技術 | 特點 |
|---|---|---|
| 邊緣/CDN | Cloudflare/阿里云 WAF、速率限制規則 | 攔截 90%+ 攻擊流量,不觸達源站 |
| Web Server | Nginx limit_req_zone、Apache mod_ratelimit | 高效能、支援突發、可白名單 |
| 應用層 (PHP) | Session/Redis 計數、Token Bucket、行為分析 | 業務感知強、可精細控制 |
| 業務邏輯 | 驗證碼、設備指紋、行為風控、人機驗證 | 針對性強、用戶體驗權衡 |
# http 區塊
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;
# server/location 區塊
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass https://php_backend;
}
location /login {
limit_req zone=login_limit burst=3 nodelay;
limit_req_status 429;
proxy_pass https://php_backend;
}
exit 無日誌:無法事後分析攻擊源、調整策略 → 結構化日誌入 ELK/Loki。$_SERVER['REMOTE_ADDR'] 可能是 IPv6,儲存/比較需統一格式。<?php
class RateLimiter {
private Redis $redis;
private array $rules = []; // ['route_pattern' => [limit, window, burst]]
public function __construct(Redis $redis) { $this->redis = $redis; }
public function addRule(string $pattern, int $limit, int $window, int $burst = 0): self {
$this->rules[$pattern] = [$limit, $window, $burst];
return $this;
}
public function handle(string $route, string $identifier = ''): bool {
$identifier = $identifier ?: $_SERVER['REMOTE_ADDR'];
foreach ($this->rules as $pattern => [$limit, $window, $burst]) {
if (fnmatch($pattern, $route)) {
return $this->check($identifier, $limit, $window, $burst);
}
}
return true; // 無規則放行
}
private function check(string $id, int $limit, int $window, int $burst): bool {
$key = "rl:$id";
$now = microtime(true);
$pipe = $this->redis->pipeline();
$pipe->zRemRangeByScore($key, 0, $now - $window);
$pipe->zCard($key);
$pipe->zAdd($key, $now, "$now:" . random_bytes(4));
$pipe->expire($key, $window + 1);
[$_, $count] = $pipe->execute();
$effectiveLimit = $limit + $burst;
if ($count >= $effectiveLimit) {
$this->logBlock($id, $count, $limit);
return false;
}
return true;
}
private function logBlock(string $id, int $count, int $limit) {
error_log(json_encode([
'time' => date('c'),
'type' => 'rate_limit',
'identifier' => $id,
'count' => $count,
'limit' => $limit,
'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
]));
}
}
// 使用
$limiter = new RateLimiter($redis);
$limiter->addRule('/api/*', 100, 60, 20)
->addRule('/login', 5, 300, 2)
->addRule('/register', 3, 3600, 1);
if (!$limiter->handle($_SERVER['REQUEST_URI'])) {
http_response_code(429);
exit('Too Many Requests');
}
核心原則:邊緣攔截 > 伺服器限流 > 應用限流 > 業務風控。PHP 層面作為「最後一道防線」與「業務感知控制」,核心邏輯用 Redis 滑動窗口,配置下發化、日誌結構化、監控告警化。