Home  >  Article  >  Backend Development  >  ob_flush(),flush()无法正常工作

ob_flush(),flush()无法正常工作

WBOY
WBOYOriginal
2016-06-06 20:46:371207browse

已查找php手册,但没有找到问题的原因。具体如下。

代码一:能正常工作的代码

<code class="lang-php"><?php set_time_limit(0);
ob_start();

$i = 1;

while (true) {
    echo str_pad(' ', 4096);
    echo $i++, '<br />';
    ob_flush();
    flush();
    sleep(1);
}
?>
</code>

代码二:不能工作的代码

<code class="lang-php"><?php set_time_limit(0);
ob_start();

echo str_pad(' ', 4096);
ob_flush();
flush();

$i = 1;

while (true) {
    echo $i++, '<br />';
    ob_flush();
    flush();
    sleep(1);
}
?>
</code>

代码二中,先输出str_pad(' ', 4096),接着再循环输出1,2,3,……,与代码一的区别仅在于代码一每次循环都需要echo str_pad(' ', 4096),为什么代码二无法正常运行。

运行环境:
win + php5.3.8

回复内容:

已查找php手册,但没有找到问题的原因。具体如下。

代码一:能正常工作的代码

<code class="lang-php"><?php set_time_limit(0);
ob_start();

$i = 1;

while (true) {
    echo str_pad(' ', 4096);
    echo $i++, '<br />';
    ob_flush();
    flush();
    sleep(1);
}
?>
</code>

代码二:不能工作的代码

<code class="lang-php"><?php set_time_limit(0);
ob_start();

echo str_pad(' ', 4096);
ob_flush();
flush();

$i = 1;

while (true) {
    echo $i++, '<br />';
    ob_flush();
    flush();
    sleep(1);
}
?>
</code>

代码二中,先输出str_pad(' ', 4096),接着再循环输出1,2,3,……,与代码一的区别仅在于代码一每次循环都需要echo str_pad(' ', 4096),为什么代码二无法正常运行。

运行环境:
win + php5.3.8

PHP中默认的buffer是4096kb,在output到达buffer大小前都会缓存起来,调用flush可以输出buffer中的内容到client。

至于你说的第二个例子不起作用问题,我觉得可能是因为PHP中默认是开启了buffer的,这时候的buffer level是1,你再使用ob_start,buffer level就变为2了,现在flush的内容还是被缓冲到level为1的buffer中,而还未到达默认buffer的size,就不能间隔输出内容了。

另外第二个地理,你可以去掉开头的ob_start调用,应该就有效果。

cache需要达到一定的长度才会在浏览器输出显示的.

Forccy的回答基本正确。稍作补充:
首先,使用如下的方式开启缓存:

<code class="lang-php">    if (ob_get_level() == 0) ob_start();
</code>

代码二中

<code class="lang-php">    echo str_pad(' ', 4096);
</code>

向缓冲区中输入了4096字节的内容,这时是不会向下一级别的缓冲区输出的。只有超出了这个容量才会输出。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn