实现表单校验后插入JSON文件的PHP代码原先可用现运行报错
代码报错排查与修复方案
高频报错原因(与数月未改动、突然失效的场景匹配)
- 服务器PHP版本自动升级,开启了严格错误校验
原代码未对$_POST参数做存在性判断,PHP 7.4+版本下,未定义的数组键会触发警告;PHP 8.x版本下,若str_word_count接收到非字符串类型参数(比如参数缺失时传入null),会直接抛出TypeError中断执行。 data.json文件状态异常
若文件被误删、此前某次写入异常导致文件内容为空/格式损坏,json_decode会返回null,后续执行array_push(null, $data)时会触发类型错误,因为array_push要求第一个参数必须为数组。- 文件权限/路径漂移
服务器重启、站点配置调整后,原代码使用的相对路径data.json可能定位错误,或运行PHP的用户失去了对data.json的读写权限,导致文件读写失败。
对应修复代码
// 兼容参数缺失场景,设置默认空值 $postTitle = $_POST['postTitle'] ?? ''; $postBody = $_POST['postBody'] ?? ''; $postTitlePass = "no"; $postBodyPass = "no"; // 强制将参数转为字符串,避免类型校验报错 if (str_word_count((string)$postTitle) >= 1) { $postTitlePass = "yes"; } if (str_word_count((string)$postBody) >= 40) { $postBodyPass = "yes"; } if ($postTitlePass == "yes" && $postBodyPass == "yes") { $postData = [ 'postTitle' => $postTitle, 'postBody' => $postBody ]; // 用绝对路径定位文件,避免路径漂移问题 $jsonFilePath = __DIR__ . '/data.json'; $fileContent = file_get_contents($jsonFilePath); // 解码为关联数组,增加格式异常兜底 $tempArray = json_decode($fileContent, true); if (!is_array($tempArray)) { $tempArray = []; } array_push($tempArray, $postData); // 增加JSON_UNESCAPED_UNICODE避免中文存储乱码 $jsonData = json_encode($tempArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); file_put_contents($jsonFilePath, $jsonData); }
额外校验步骤
- 检查
data.json的权限设置,确保运行PHP的进程用户(如www-data、nginx)对该文件拥有读写权限 - 确认表单提交的请求方法为POST,且表单字段名与代码中的
postTitle、postBody完全匹配
内容的提问来源于stack exchange,提问作者Emily Zakkak
相关产品推荐
相关产品推荐

