Output before the header is tested
<?php
echo ' Hello world! ';
Header (' content-type:text/html;charset=utf-8; ');
I was tested to succeed without any errors or warnings. I don't know what you guys are like? But I think most of it is no problem, if there is Cannot modify header information - headers already sent such a warning, this is to say can not modify the head information, the head information has been sent. Come down and see why there are two different outcomes.
Buffer
As a metaphor, it's like a cache when we watch a movie. It will not immediately play out to us, but first part of the downloaded good movie into the cache, and then there is a cache playback. That's why we write PHP code.
The caching mechanism of PHP-output_buffering
Common functions in PHP ob
Ob_start: Open Output buffer
Ob_clean: Empty buffer
Ob_get_contents: Return buffer contents
Ob_get_clean: Returns the contents of the buffer and empties
<?php
Ob_start ();
echo ' Hello world! ';
echo ob_get_contents ()//output Hello World!hello world!
In the php.ini configuration file, modify the buffer size
Typically around 233 lines, the default is 4096 means 4096 bytes is 4kB
Down to change 4096 to 5, rerun this code
<?php
echo ' Hello world! ';
Header (' content-type:text/html;charset=utf-8; ');
There is no warning or error for the test just now, and the error is:Cannot modify header information - headers already sent
Analysis between header and buffer
Why we didn't have output before the header.
For the header function, it is like sending the original HTTP header to the client, declaring what the page we are writing is exactly what it is, so once the statement is wrong, it does not conform to the HTTP rules.
Come down and talk about headers in PHP.
In PHP, the header is not passed through the buffer, and it is exported directly to the client via the server
Explain the previous warning cannot modify header information
When we write some output before the header, it passes through the buffer first. So even if you write the front, the final output order or header in the first echo .
But the contents of our output buffer, that is, the previous output ' hello world!' > 5 bytes. It's going to go straight out, which means that you lose it, and then 出'hello world' header(...), you break the real header without the output.
Summarize
In practice, we'd better write the header at the top of the page. Because we're not sure if the output before our header is buffered. I hope this article for you to learn PHP help.