6

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?

2
  • It depends somewhat on some settings set in the php.ini config. Although it doesn't make much sense to change the HTTP headers after output anyways, so one should always structure the program in such a way that headers are called before output. Commented Sep 17, 2017 at 11:06
  • A "header" is by definition "ahead" of any content/output. Commented May 20, 2021 at 16:50

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

To get an error you need set directive output_buffering = Off or comment it ";" in php.ini file

Comments

-1

edit your php.ini and enable Output Buffering ..

1 Comment

Asker already has some form of output buffering enabled if they aren't getting an error with that code sample.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.