如何检查标头是否已在 PHP 中发送

2022-01-11 00:00:00 header php

我想我们大多数人都知道 PHP 中臭名昭著的标头已发送"错误.我可以检查一下是否已经发送了标头吗?

I think most of us know about the infamous "Headers already sent" error in PHP. Can I check someway if headers already have been sent?

在全力以赴尝试设置一些 SESSION 数据或类似数据之前,这样做真的很方便.

It would be really handy to do such, before going all out with trying to set some SESSION data or similar.

谢谢!

推荐答案

PHP有一个函数 headers_sent() 允许您在采取任何操作之前检查标头是否已发送出去.以下是在代码中使用该函数的方法:

PHP has a function headers_sent() which allows you to check if the headers are already sent out before you take any action. Here’s how you could use the function in your code:

if(headers_sent())
{ //if headers already sent out print some message.
echo "Please go to yahoo.com";
}
else{
//send the user automatically to test.php
header('Location: http://yahoo.com');
exit;
}

相关文章