Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

header - PHP buffer why

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 .= "
<span></span>
";

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 <tag> 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 .

//EDIT REGARDING HEADERS

If I don't add , an HTML tag, and a second set of , 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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, why do I need to send the <tag> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...