Blog Details
PHP防止批量请求
发布作者
Project
发布时间
20 June, 2022
Post by
Gilbert Smith
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium deleniti atque corrupti quos dolores et quas molestias excepturi sint quidem rerum facilis est
以下是PHP防止批量请求的代码实现,主要通过IP限制和请求频率控制来实现:
<?php // 设置IP请求限制 function preventFloodRequests() { $ip = $_SERVER['REMOTE_ADDR']; $cacheDir = __DIR__.'/cache/'; $cacheFile = $cacheDir.$ip.'.tmp'; // 创建缓存目录 if(!is_dir($cacheDir)) { mkdir($cacheDir, 0755, true); } // 限制每分钟最多30次请求 $maxRequests = 30; $timeLimit = 60; // 60秒 if(file_exists($cacheFile)) { $data = json_decode(file_get_contents($cacheFile), true); $currentTime = time(); // 如果还在时间限制内且超过最大请求数 if(($currentTime - $data['first_request']) < $timeLimit) { if($data['count'] >= $maxRequests) { header('HTTP/1.1 429 Too Many Requests'); die('请求过于频繁,请稍后再试'); } $data['count']++; } else { // 重置计数器 $data = [ 'first_request' => $currentTime, 'count' => 1 ]; } } else { $data = [ 'first_request' => time(), 'count' => 1 ]; } file_put_contents($cacheFile, json_encode($data)); } // 调用防护函数 preventFloodRequests();
这段代码会记录每个IP地址的请求频率,如果同一IP在60秒内请求超过30次,将返回429状态码并阻止后续请求。你可以将此代码包含在需要保护的PHP文件开头。
Title:
- Donec sodales sagittis
- Sed consequat leo eget
- Aliquam lorem ante
- Aenean ligula eget
- Cum sociis natoque
Comments :
Delores Williams 1 hr Ago
If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual

Leave a Reply:
Search
Categories
Upcoming Post
Popular Post
Tag Clouds
Instagram Post





