The secret between the php buffer and the header function is whether we have heard of the actual output before the header in actual development. Some even think that the header function must be written at the beginning of the code. But have you tried the header function before outputting? Let's take a deeper look.
- Output before test header
When I pass the test, I will succeed without any errors or warnings. I don't know how you are? But I think most of them are okay. if a warning like Cannot modify header information-headers already sent is reported, it means that the header information Cannot be modified and the header information has been sent. Next, let's take a look at why there are two different results?
Buffer Zone
A metaphor is like the cache when we watch a movie. It will not immediately play the video between us, but will first put some of the downloaded movies into the cache, and then play them out in the cache. This is why we write php code.
Php Cache mechanism-output_buffering
- Common ob functions in php
Function |
Explanation |
Ob_start |
Open output buffer |
Ob_clean |
Clear the buffer |
Ob_get_contents |
Returned buffer content |
Ob_get_clean |
Return the buffer content and clear it. |
- Modify the buffer size in the php. ini configuration file.
Usually around 233 rows. the default value is 4096, which indicates 4096 bytes, which is 4 kB.
Change 4096 to 5 and run the code again.
If no warning or error occurs during the test, the error is:Cannot modify header information-headers already sent
Analysis between header and buffer
Why is there no output before we say the header?
For the header function, it is like sending the original http header to the client, which declares what the webpage we are writing is, so it is wrong if there is content before this declaration, does not comply with http rules
Let's talk about the header in php.
In php, the header does not pass through the buffer zone and is directly output to the client through the server.
Interpret the previous warning Cannot modify header information
When we write some output before the header, it will first pass through the buffer zone. Therefore, even if you write the preceding code, the final output sequence is echo first.
However, the output content cache cannot be placed, that is, the previous output 'Hello world! '> 5 bytes. It will be output directly, that is, output 'Hello world' first and then header (...), which violates the actual header and cannot be output before
Summary
In practice, we 'd better write the header at the top of the page. Because we are not sure whether the buffer of the output content before our header can be put down.