Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call header() after output is sent

Tags:

php

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?

like image 601
zer0uno Avatar asked Mar 08 '23 01:03

zer0uno


1 Answers

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.

like image 165
axiac Avatar answered Mar 19 '23 19:03

axiac