headers_sent() 函数检测 HTTP 头是否已经发送。
bool headers_sent ([ string &$file [, int &$line ]] )
检测 HTTP 头是否已经发送。
HTTP 头已经发送时,就无法通过 header() 添加更多头字段。 使用此函数起码可以防止 HTTP 头出错。另一个解决方案是用 输出缓冲。
HTTP 头未发送时,headers_sent() 返回 FALSE,否则返回 TRUE。
| 序号 | 参数和说明 |
|---|---|
| 1 | file 若设置了可选参数 file 和 line, headers_sent() 会把 PHP 文件名放在 file 变量里, 输出开始的行号放在 line 变量里。 |
| 2 | line 输出开始的行号。 |
试试下面的实例
<?php
if (!headers_sent()) {
header('Location: http://www.nhooo.com/');
exit;
}
if (!headers_sent($filename, $linenum)) {
header('Location: http://www.nhooo.com/');
exit;
} else {
echo "Headers already sent in $filename on line $linenum\n" .
"Cannot redirect, for now please click this <a " .
"href = \"http://www.nhooo.com\">link</a> instead\n";
exit;
}
?>上面的示例将检查标头是否已发送,如果已发送,则显示一条消息,否则将发送标头