PHP Header函数报错:检测到换行,资产更新后无法跳转
PHP Header跳转报错及资产更新后跳转异常解决
问题情况
Warning: Header may not contain more than a single header, new line detected in .... line 65
点击资产更新按钮后,页面停留在更新页,无法跳转到目标资产展示页;预期效果是跳转后弹出更新成功提示。该页面此前运行正常,系统内其他更新/插入类脚本也无异常。
涉及代码
更新操作核心代码:
$stmt = $pdo->prepare('UPDATE assmgnt SET id = ?, name=?,manufacturer=?,model=?,description=?,type=?,size=?,consumable=?,serialnum=?,licnum=?,accdetails=?,fueltype=?,location=?,resperson=?,status=?,purchfrom=?,datepurch=?,price=?,quantity=?,fundsource=?,receipt=? WHERE id=?'); $stmt->execute([$id,$name,$manufacturer,$model,$description,$type,$size,$consumable,$serialnum,$licnum,$accdetails,$fueltype,$location,$resperson,$status,$purchfrom,$datepurch,$price,$quantity,$fundsource,$receipt,$_GET['id']]); header('Location: display.php?id='.$id); $_SESSION['status'] = "The asset information has been successfully updated.";
报错关联代码行:
header('Location: display.php?id='.$id);
问题排查与解决方法
1. 清洗变量中的换行/空白字符
报错提示Header存在换行,大概率是$id变量中包含了隐藏的换行符(比如表单提交时带入、数据库读取时残留),导致拼接后的跳转URL包含换行,触发Header验证错误。
处理方式:对$id做清洗,去除多余空白和换行:
$cleanId = trim($id); header('Location: display.php?id='.$cleanId);
2. 调整代码顺序并添加终止语句
当前代码中会话提示设置在Header跳转之后,逻辑上应先设置提示再跳转;同时必须添加exit或die()确保后续代码不再执行,避免意外输出干扰Header发送:
// 先设置成功提示 $_SESSION['status'] = "资产信息已成功更新。"; // 清洗ID并跳转 $cleanId = trim($id); header('Location: display.php?id='.$cleanId); exit; // 终止脚本执行,防止后续输出
3. 检查页面前置输出
确认更新页面的PHP代码开头(<?php标签之前)没有任何空白字符、HTML代码或echo输出,哪怕一个空格或换行都会导致Header无法正常发送。
内容的提问来源于stack exchange,提问作者PJJ
相关产品推荐
相关产品推荐

