Abhishek Agarwal
Abhishek Agarwal

Reputation: 724

Headers are being sent although output already sent

For what I know is it is not possible to send HTTP headers after your output has been sent and only way to workaround is to use output buffering

But my PHP script is able to send headers even after output is sent. here is my code

Text output already sent
<?php
header('Location: test2.php');
die();
?>

Why is this code not giving error for "HTTP headers already sent" Is there another way to turn output buffering on?

EDIT:

I am running it on my localhost using wamp

No files are included in the above code

I just noticed outbut_buffering directive in phpinfo() which is set to 1 But when I check it in php.ini file it is set to Off

Upvotes: 2

Views: 167

Answers (3)

Brejk
Brejk

Reputation: 454

You can check if and where headers have been sent with headers_sent function:

if (!headers_sent($filename, $linenum)) {
    header('Location: test2.php');
    exit;
} else {
    echo 'Headers sent from '. $filename;
}

Then check the $filename.

Upvotes: 1

stepozer
stepozer

Reputation: 1181

You don't see error because output buffering enabled. Try this code:

<?php
ob_end_clean();
?>
Text output already sent
<?php
header('Location: test2.php');
die();
?>

It return error:

Text output already sent Warning: Cannot modify header information - headers already sent by

Upvotes: 1

udondan
udondan

Reputation: 59989

You are right, this should not work.

First, are you sure the headers are written, or do you simply wonder why there is no error message shown? Maybe error reporting is turned off? In that case try to increase the error reporting level:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Remove this from your code when you're finished debugging. Errors should be logged to a log file and never be shown in productive environment!

Also, check if the header is really sent. You can do that with wget for example:

wget -S http://example.com/

or curl:

curl -v http://example.com/

You can as well see the HTTP headers in Chromes developer console. In other browsers most probably too.

If the header is really sent, then there probably is some magic regarding output buffering in place. Are you running this locally or on a remote host? If this is not your host, it might be the provider has set this up. PHP has a feature to automatically prepend and append custom code. Check the php.ini settings for auto_prepend_file and auto_append_file. There could be some ob_start() etc. hidden. You can see all PHP settings by calling phpinfo() or one specific with ini_get().

Upvotes: 2

Related Questions