如何使用PHP替换.htaccess文件中的内容实现封禁IP解禁?
核心问题排查
- 前端输出复选框时未提取IP值,
$ip变量未定义,导致复选框value为空,后端收到的iplist没有有效内容 - 替换逻辑错误:仅替换IP字符串会残留
deny from无效内容,且可能误删其他规则里的IP字符,应该匹配整行deny from 选中IP的规则再删除 - 后端代码中
$htaccess变量未定义路径,无法找到.htaccess文件,读写操作直接失效 - 未做文件权限校验,若.htaccess没有web运行用户的写入权限,修改会静默失败
- 多选IP时循环发送多次AJAX请求容易出现并发错误,建议批量提交更稳定
修复后代码
1. IP列表展示代码
$base = $_SERVER["DOCUMENT_ROOT"]; $htaccess = $base."/.htaccess"; // 先判断文件是否存在可读 if (!is_file($htaccess) || !is_readable($htaccess)) { echo ".htaccess文件不存在或不可读"; exit; } $contents = file_get_contents($htaccess); // 用PHP_EOL适配不同操作系统的换行符 $lines = explode(PHP_EOL, $contents); ?> <table width='50%'> <?php foreach($lines as $line) { // 加捕获组提取IP地址 if (preg_match('/^deny from (\d{1,3}(?:\.\d{1,3}){3})$/', $line, $matches)) { $ip = $matches[1]; ?> <tr> <td><?php echo $line;?></td> <td style='text-align:center'><input type='checkbox' name='ipCheck' value='<?php echo $ip;?>'></td> </tr> <?php } } ?> </table> <table> <tr> <td></td> <td><button id="allowIPbtn" name="allowIPbtn" class='btn'>Allow selected IPs</button></td> </tr> </table>
2. jQuery提交代码
$(document).ready(function () { $('#allowIPbtn').click(function () { let checkedIps = []; // 收集所有选中的IP $("input:checkbox[name=ipCheck]:checked").each(function () { checkedIps.push($(this).val()); }); if (checkedIps.length === 0) return; $("#overlay").show(); // 批量提交所有选中IP $.ajax({ type: 'post', data: {iplist: checkedIps}, success: function(data){ $("#overlay").hide(); // 刷新页面更新列表 location.reload(); }, error: function(){ $("#overlay").hide(); alert("操作失败,请检查文件权限"); } }); }); });
3. 后端处理代码
ob_start(); if(isset($_POST['iplist']) && is_array($_POST['iplist'])){ $base = $_SERVER["DOCUMENT_ROOT"]; $htaccess_file = $base."/.htaccess"; // 校验文件可写 if (!is_file($htaccess_file) || !is_writable($htaccess_file)) { echo "文件不可写,请检查权限"; exit; } $ipSelected = $_POST['iplist']; $lines = file($htaccess_file, FILE_IGNORE_NEW_LINES); $newLines = []; foreach ($lines as $line) { $needDelete = false; foreach ($ipSelected as $selectedIP) { if (trim($line) === "deny from ".$selectedIP) { $needDelete = true; break; } } if (!$needDelete) { $newLines[] = $line; } } // 拼接内容写入文件 file_put_contents($htaccess_file, implode(PHP_EOL, $newLines)); echo "success"; exit; }
注意事项
- 确保.htaccess文件权限设置为755,或者所属用户为web运行用户(如www-data、apache),保证可写入
- 操作前建议备份.htaccess文件,避免规则误删
- 若使用CDN等代理服务,注意封禁IP不要误封CDN节点地址
内容的提问来源于stack exchange,提问作者CharlieT
相关产品推荐
相关产品推荐

