|
- function check_ip_frequency($limit = 5, $time_frame = 60) {
- // 获取用户的 IP 地址
- $user_ip = $_SERVER['REMOTE_ADDR'];
- $cookie_name = 'ip_access_times_' . md5($user_ip); // 使用 IP 地址生成唯一的 Cookie 名称
- // 获取当前时间
- $current_time = time();
- // 检查 Cookie 是否存在
- if (isset($_COOKIE[$cookie_name])) {
- // 解码 Cookie 中的访问时间数组
- $access_times = json_decode($_COOKIE[$cookie_name], true);
- } else {
- $access_times = []; // 初始化访问时间数组
- }
- // 清理过期的访问记录
- $access_times = array_filter($access_times, function($time) use ($current_time, $time_frame) {
- return ($current_time - $time) < $time_frame;
- });
- // 添加当前访问时间
- $access_times[] = $current_time;
- // 检查访问次数是否超过限制
- if (count($access_times) > $limit) {
- header("HTTP/1.1 404 Not Found");
- exit; // 终止脚本执行
- }
- // 更新 Cookie,设置过期时间为 $time_frame 秒
- setcookie($cookie_name, json_encode($access_times), $current_time + $time_frame, "/");
- }
- // 使用示例
- check_ip_frequency(5, 60); // 限制每分钟最多访问 5 次
复制代码
|
温馨提示:本网站所展示的内容均由注册会员自行发布,这些内容仅代表作者本人的观点和立场,并不代表本网站的官方立场或意见。我们致力于打造一个开放的社区平台,鼓励用户自由表达和分享信息。然而,我们也明确声明,对于用户发布的内容,我们不承担任何法律责任。
|