headers_sent

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

headers_sent檢測(cè) HTTP 頭是否已經(jīng)發(fā)送

說明

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

檢測(cè) HTTP 頭是否已經(jīng)發(fā)送。

HTTP 頭已經(jīng)發(fā)送時(shí),就無法通過 header() 添加更多頭字段。 使用此函數(shù)起碼可以防止 HTTP 頭出錯(cuò)。另一個(gè)解決方案是用 輸出緩沖

參數(shù)

file

若設(shè)置了可選參數(shù) file and line, headers_sent() 會(huì)把 PHP 文件名放在 file 變量里, 輸出開始的行號(hào)放在 line 變量里。

line

輸出開始的行號(hào)。

返回值

HTTP 頭未發(fā)送時(shí),headers_sent() 返回 false,否則返回 true。

范例

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

<?php

// 沒有 HTTP 頭就發(fā)送一個(gè)
if (!headers_sent()) {
    
header('Location: http://www.example.com/');
    exit;
}

// 使用 file 和 line 參數(shù)選項(xiàng)的例子
// 注意 $filename 和 $linenum 用于下文中使用
// 所以不要提前為它們賦值
if (!headers_sent($filename$linenum)) {
    
header('Location: http://www.example.com/');
    exit;

// 很有可能在這里觸發(fā)錯(cuò)誤
} 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;
}

?>

注釋

注意:

數(shù)據(jù)頭只會(huì)在SAPI支持時(shí)得到處理和輸出。

參見

  • ob_start() - 打開輸出控制緩沖
  • trigger_error() - 產(chǎn)生一個(gè)用戶級(jí)別的 error/warning/notice 信息
  • headers_list() - 返回已發(fā)送的 HTTP 響應(yīng)頭(或準(zhǔn)備發(fā)送的)
  • header() - 發(fā)送原生 HTTP 頭 中有更多相關(guān)細(xì)節(jié)的討論。