为什么 flush() 不立即执行数据? php

why is flush() not executing data right away? php

我正在编写 PHP 脚本,但卡在了 flush() 函数上。这是我的脚本:

<?php
    echo "1";
    flush();
    sleep(5);
    echo "2";
?>

我希望我的脚本发送“1”,然后等待 5 秒,然后发送“2”。但是脚本等待 5 秒,然后发送“12”。我一直在寻找过去几个小时的答案,但找不到适合我的答案。

首先

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser.

其次

It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

http://php.net/manual/en/function.flush.php

至少,也尝试调用 ob_flush()

如果您将它与某种网络服务器一起使用,您还需要使用 ob_flush()ob_flush 必须总是在 flush() 之前。

因此您的代码将是:

<?php
    echo "1";
    ob_flush();
    flush();
    sleep(5);
    echo "2";
?>