According to the PHP documentation:
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
but when I tried the example that the documentation reports (with a little change):
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('X-Header: http://www.example.com/');
exit;
?>
all worked just fine, no error poped up and I smoothly got my <html>
tag in the output and my X-Header
in the headers.
I'm using PHP 7.1.9, so is still correct what the documentation says?
The documentation is still correct.
For performance purposes, the interpreter puts the output in a buffer. When the buffer is filled for the first time, the interpreter sends the headers then it sends the content of the buffer (and empties the buffer). After this point any call of the function header()
fails. The headers cannot be modified any more and other headers cannot be added because the headers have already been sent.
This lets the script produce a small amount of output before sending the headers.
Read more about output buffering configuration settings.
The option output_buffering
allows turning the feature off or on and even setting the size of the buffer.
The option implicit_flush
tells the interpreter to flush the buffer after every output block. This forces your script to send the headers correctly, before any output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With