You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FileMaker API for PHP登录页报错:Cannot modify header information

解决 "Cannot modify header information - headers already sent" 错误

这个错误是PHP开发里非常常见的问题,核心原因一句话就能说清:header()函数必须在任何实际输出(包括HTML标签、空格、换行、甚至PHP注释之外的内容)发送到浏览器之前调用。

看你的代码,在执行第56行的header("location:LoginSuccess.php");之前,第22行之前已经输出了<html>、<head>标签,还有页面里的注释内容——这些都会被当作HTTP响应的一部分先发送出去,导致HTTP头部已经被确定,没法再修改跳转的header了。

具体修复步骤

把所有的HTML输出(包括页面结构、表单、提示信息)都移到PHP登录逻辑的后面,确保只有当不需要跳转(登录失败或者首次访问)的时候才输出HTML内容。修改后的代码如下:

<?php 
# 必须在任何输出之前启动session
session_start(); 
$_SESSION['login']=0; 

include ("../../Conn/dbaccess.php"); 

$message = 'Please enter a user name and password.';

# 先处理登录逻辑,这部分完全没有输出
if(isset($_POST['Login']) and (!empty($_POST['username']) and !empty($_POST['password'])) ) { 
    $username = '==' . urldecode($_POST['username']); 
    $password = md5($_POST['password']); 

    $request = $fm->newFindCommand('Demo php'); 
    $request->addFindCriterion('UserName', $username); 
    $request->addFindCriterion('Password', $password); 
    $result = $request->execute(); 

    if (FileMaker::isError($result)) { 
        $request = $fm->newFindAllCommand('Demo php'); 
        $result = $request->execute(); 
    } 

    $found = $result->getFoundSetCount(); 
    if($found == 1) { 
        $_SESSION['login']=1; 
        // 这里调用header之前,完全没有任何HTML输出
        header("location:LoginSuccess.php"); 
        exit; // 跳转后必须exit,避免后续代码执行
    } else { 
        $_SESSION['login']=0; 
        $message = 'Incorrect user name or password.'; 
    } 
} 
?>

<!-- 所有HTML输出都在PHP逻辑之后,只有当不跳转的时候才会输出 -->
<html> 
<head> 
<title>Login</title> 
</head> 
<body> 
<!-- 页面注释可以保留在这里,因为已经在PHP逻辑之后了 -->
<form action="Login.php" method="post"> 
<table border="0" cellspacing="3" cellpadding="3"> 
<tr> 
<td>&nbsp;</td> 
<td><?php echo $message; ?></td> 
</tr> 
<tr> 
<td>User Name</td> 
<td><input name="username" type="text" /></td> 
</tr> 
<tr> 
<td>Password</td> 
<td><input name="password" type="password" /></td> 
</tr> 
<tr> 
<td>&nbsp;</td> 
<td><input name="Login" type="submit" value="login" /></td> 
</tr> 
</table> 
</form> 
</body> 
</html>

额外注意事项

  • 检查../../Conn/dbaccess.php文件:确保这个文件的开头<?php之前没有任何空格、换行或者其他字符,否则这个include的文件也会提前输出内容,导致同样的错误。
  • 不要在session_start()之前添加任何空白字符或者输出,你的代码这部分是正确的,但要保持这个习惯。
  • 调用header()之后一定要加上exit;或者die();,避免后续的HTML代码继续执行并输出。

内容的提问来源于stack exchange,提问作者mr buffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:56:01