Text before php header not giving errors

I'm new to development and I'm trying to learn php.



Why is it that when I use the code below, the redirection, (through the header syntax), is still taking place even though content has been output before it ?



<html>
<body>
<p>My Page</p>
</body>
</html>

<?php

$redirect_page = 'http://localhost';
$redirect = true;
echo "Some Text";
if($redirect==true){
header('Location: '.$redirect_page);
}
?>


Many thanks in advance



Answers

HTTP requires response headers to arrive strictly before the body content, like so:



HTTP/1.1 200 OK
Powered-By: PHP/7.0.0-20150527
Content-Type: text/html; charset=utf-8

<html><body>Hello world!</body></html>


For PHP to comply with that requirement, PHP must send all accumulated headers at the instant it's ready to send any body content. The answer to your question hinges on the definition of when PHP is "ready to send".



To figure that out, look at your output_buffering setting:



var_dump(ini_get('output_buffering'));


On my machine with default settings, that returns 4096, which according to the manual means that PHP will be "ready to send" when 4096 body bytes have been accumulated.



To get the page to behave as you expect (ie, not sending the headers), you need to output enough bytes to exceed the setting of output_buffering. You can either do that by reducing the output buffering setting or by emitting more body text, eg:



echo str_repeat('<div/>', 4096);



See also this SO primer.