PHP buffer why \r\n
I have a few conceptual questions (all related, I think) regarding the following script, at the comments. The script works fine.
<?PHP
ob_start();
// Create string to overflow browser buffer ...?
$buffer = str_repeat(" ", 4096);
// Indicate new header / html content ...?
$buffer .= "\r\n<span></span>\r\n";
for ($i=0; $i<5; $i++) {
echo $buffer.开发者_开发问答$i;
ob_flush();
flush();
sleep(1);
}
ob_end_flush();
?>
First, why do I need to send the \r\n<tag>\r\n
to the browser? I assume it has something to do with headers.
Second, why do I need some HTML in the middle?
Third, there are many examples that use 256 bytes instead of 4096. However, the script doesn't work if I use 256. Are these examples outdated, and will this number change again in the future?
//EDIT REGARDING SOURCE LINKS
This code was gathered mainly from the commentary in php.net sleep()
function and the solution to this SO question. Neither mentions why to include \r\n
.
//EDIT REGARDING HEADERS
If I don't add \r\n
, an HTML tag, and a second set of \r\n
, the script will not execute properly in Chrome or Safari (it just dumps all the values at once).
Additionally, if this is called before a session_start()
, it throws an error: "Cannot send session cache limiter - headers already sent".
First, why do I need to send the
\r\n<tag>\r\n
to the browser? I assume it has something to do with headers.Second, why do I need some HTML in the middle?
Normally browser have to wait until they have fetched the whole response until it can be rendered (just think of XML that can be valid until the last character). But since that would make a bad user experience, most browsers start to parse and render the contents as early as possible.
And here this HTML fragment could be the initiator for the browser to actually build the DOM and start rendering.
Third, there are many examples that use 256 bytes instead of 4096. However, the script doesn't work if I use 256. Are these examples outdated, and will this number change again in the future?
As the manual hints that there might be some further buffering incorporated in the web server, this might be the attempt to overflow those buffers that they are also flushed in order to have the expected effect.
The reason for using \r\n
would be make the output render nicely when viewed using a Windows source viewer like notepad.exe
.
Nothing to do with headers here.
Seeing as the code uses the output buffering functions, I have no idea why they feel the need to try and overflow a 4kb buffer (the default in a standard php.ini
though more professionals would opt for no default output buffering).
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
精彩评论