headers_sent() return false, but headers were sent

寵の児 提交于 2019-12-10 17:11:20

问题


My code is simple:

<!DOCTYPE html>
<html>
  <head>
    ...

   <?php var_dump(headers_sent()); ?>

It returns false. Shouldn't the headers be sent immediately after something is printed? Like just after the first < character.


回答1:


It depends if your output_buffering directive in php.ini file. If it is Off

output_buffering = Off

then echo headers_sent() should output 1

In other cases, headers_sent() won't output any results because it will be FALSE. The headers won't be sent because the output is buffered.

If you want to get around this and force-send headers, you can use flush().

Hope this helps!




回答2:


Read the comments in docs!

Here, for example: http://es1.php.net/manual/en/function.headers-sent.php#75835

He do a great exposition :P

Edit

Yes, headers_sent() will return false, even if you sent something to the ouptut using print() or header() , if output_buffering is different from Off in you php.ini, and the length of what you sent does not exceed the size of output_buffering. [...] This is noticed in php.ini comment : "Output buffering allows you to send header lines (including cookies) even after you send body content, in the price of slowing PHP's output layer a bit."




回答3:


I managed to find a way without deactivating the output_buffering :

if (!headers_sent() && !ob_get_contents()) {
    // do your thing
}


来源:https://stackoverflow.com/questions/17588563/headers-sent-return-false-but-headers-were-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!