Home > Article > Backend Development > Is there any way in PHP to detect whether there is any output before the program runs here?
Note that I am not trying to solve the problem of header(), but there is a function in the program that has this requirement.
On the contrary, I have thought about whether I can detect it by sending a header, or set a cookie (a truth). But it is said that PHP has an output_buffering mechanism, which makes this approach unworkable. Because turning this mechanism off cruelly may cause some other unexpected problems, and not all environments can be turned off.
Even if it works, the cookie is always a little slow and cannot be obtained immediately after setting it. Sending a header will cause useless things to be mixed in the http header.
That. . .
Is there any way to meet this demand?
(I don’t want to modify the code in other parts of the program)
Note that I am not trying to solve the problem of header(), but there is a function in the program that has this requirement.
On the contrary, I have thought about whether I can detect it by sending a header, or set a cookie (a truth). But it is said that PHP has an output_buffering mechanism, which makes this approach unworkable. Because turning this mechanism off cruelly may cause some other unexpected problems, and not all environments can be turned off.
Even if it works, the cookie is always a little slow and cannot be obtained immediately after setting it. Sending a header will cause useless things to be mixed in the http header.
That. . .
Is there any way to meet this demand?
(I don’t want to modify the code in other parts of the program)
Using headers_sent()
to determine whether the header is sent can meet your needs? If the content has been output, the headers must have been sent.
php’s output mechanism does not output commands immediately after using echo
, but instead puts this part of the content into a buffer first. (The so-called buffer is a piece of shared memory). When the memory is full or the script ends, PHP will deliver this memory to nginx or apache for output.
So, to achieve your needs, you only need to determine whether there is content in the buffer.
php provides us with such a function, namely ob_get_contents