I have some problems with header() function. It works and doesn’t work at the same time.
The manual says:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
Otherwise there will be an error.
But I can call header() anywhere in the html-script or php code after the output has been sent and header() works:
<?php
echo "Output here";
header("Location: http://stackoverflow.com"); // it works, it redirects to the site
echo "And output here";
?>
Any header() works. This one header("Some-Header: bar-foo") can set header:
<!DOCTYPE html>
<html>
<body>
… some script here…
<?php
print_r(headers_list()); // only one header: [0] => X-Powered-By: PHP/5.3.5
header("Some-Header: bar-foo")
print_r(headers_list()); // two headers: [0] => X-Powered-By: PHP/5.3.5
[2] => Some-Header: bar-foo
var_dump(headers_sent($file, $line)); // bool(false)
var_dump($file); // string(0) ""
var_dump($line); // int(0)
?>
… some script here…
</body>
</html>
How can it be? Is there something wrong with settings?
Chances are the
php.inihas output_buffering enabled which is the exception to the rule. e.g.(Note:
ob_startisn’t necessary in the script file if the ini hasoutput_bufferingenabled, but wanted to demonstrate the premise through code)