php 检测 HTTP 头是否已发送的方法

180it 2021-05-18 PM 921℃ 0条

在多人协同搞一个php项目时,有时候不确实页面的HTTP头是否已发送,就需要判断一下,如果HTTP头没有发送过就可以发送一次,而PHP脚本也提供一个判断HTTP头是否已发送的函数 headers_sent().

php headers_sent() 函数介绍
headers_sent():检测HTTP头是否已发送,如果已发送返回 TRUE ,如未发送返回 FALSE

语法:

headers_sent ($file = ? , &$line = ? )
复制
参数:

若设置了可选参数 file 和 line,则 headers_sent() 会把 php 文件名放在 file 变量里,输出开始行号放在 line 变量里。

file:php文件名

line:输出开始的行号

php 判断http头是否已发送的方法
例1:php 判断是否定义了页面的编码

if (!headers_sent()) {

header('Content-type: text/html; charset=utf-8');

}
复制
例2:php 判断是否已发送HTTP头的方法

header('content-type:text/html;charset=utf-8');
echo 'feiniaomy.com
';
ob_end_flush();
if(headers_sent()){

echo 'HTTP头已发送!';

}else{

echo 'HTTP头未发送!';

}
复制
例3:headers_sent() 使用参数的方法

header('content-type:text/html;charset=utf-8');
echo 'feiniaomy.com
';
ob_end_flush();
if (!headers_sent($file, $line)) {

header('content-type:text/html;charset=utf-8');
exit;

} else {

 // 很有可能在这里触发错误
echo $file;
echo '<br/>';
echo $line;
exit;

}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php 检测 HTTP 头是否已发送的方法