headers_sent 检测 HTTP 头是否已经发送

发表日期:2021-07-01 08:56:41 | 来源: | | 浏览(758) 分类:网络 函数

headers_sent

(PHP 4, PHP 5, PHP 7, PHP 8)

headers_sent检测 HTTP 头是否已经发送

说明

headers_sent(string &$file = ?, int &$line = ?): bool

检测 HTTP 头是否已经发送。

HTTP 头已经发送时,就无法通过 header() 添加更多头字段。 使用此函数起码可以防止 HTTP 头出错。另一个解决方案是用 输出缓冲

参数

file

若设置了可选参数 file and lineheaders_sent() 会把 PHP 文件名放在 file 变量里, 输出开始的行号放在 line 变量里。

line

输出开始的行号。

返回值

HTTP 头未发送时,headers_sent() 返回 false,否则返回 true

范例

示例 #1 使用 headers_sent() 的例子

<?php 
// 没有 HTTP 头就发送一个if (!headers_sent()) {
    header('Location: http://www.example.com/');
    exit;
}
// 使用 file 和 line 参数选项的例子// 注意 $filename 和 $linenum 用于下文中使用// 所以不要提前为它们赋值if (!headers_sent($filename, $linenum)) {
    header('Location: http://www.example.com/');
    exit;
// 很有可能在这里触发错误}
 else {
    echo "Headers already sent in $filename on line $linenum\n" .          "Cannot redirect, for now please click this <a " .          "href=\"http://www.example.com\">link</a> instead\n";
    exit;
}
?>

注释

注意:

数据头只会在SAPI支持时得到处理和输出。

参见

  • ob_start() - 打开输出控制缓冲
  • trigger_error() - 产生一个用户级别的 error/warning/notice 信息
  • headers_list() - 返回已发送的 HTTP 响应头(或准备发送的)
  • header() - 发送原生 HTTP 头 中有更多相关细节的讨论。

集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。