Manngo Manngo - 16 days ago 5
PHP Question

PHP: Demonstrate Headers Already Sent

Note: I am not trying to solve the

headers already sent
problem. I am trying to create one!

I thought I understood what causes this error, and I am trying to demonstrate it to some students. Here is a sample script:

Hello

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

print 'This space for rent …';

setcookie('test',12);
header('Testing');
?>


As you see, I am trying my best to send output before setting a header, either indirectly by setting a cookie, or directly using the
header()
function.

As weird as the question sounds, how can I get this error to appear?

Answer

If output buffering is on in the php.ini it won't throw the error as output is captured and sent at the end. This is sort of like the "lazy man's" way to prevent these errors instead of actually fixing the scripts causing them. You can create the error by turning this off or ending output buffering before the output with something like ob_end_clean() (then output, then header)