PHP 与 Web Server 缓冲区的区别
ob_* 系列函数主要用于操作 PHP 内部的输出缓冲区。
因此,ob_flush 函数的作用是刷新 PHP 自身的缓冲区内容。
相比之下,flush 函数严格来说仅在 PHP 作为 Apache 模块(handler 或 filter)安装时才具有实际意义。它的主要功能是刷新 Web 服务器(特指 Apache)的输出缓冲区。
在 Apache Module 的 SAPI 环境下,flush 会通过调用 sapi_module 结构体中的 flush 成员函数指针,间接调用 Apache API 中的 ap_rflush 来刷新 Apache 的输出缓冲区。需要注意的是,手册中也指出,某些其他 Apache 模块可能会改变这一行为的结果。
部分 Apache 模块,例如 mod_gzip,可能会执行自己的输出缓存机制,这会导致 flush() 函数的结果无法立即发送到客户端浏览器。
此外,浏览器端也可能在渲染前对接收到的内容进行缓存。例如,Netscape 浏览器会在接收到换行符或 HTML 标记开头之前缓存内容,并且在接收到 </table> 标记之前,不会显示整个表格的内容。
一些版本的 Microsoft Internet Explorer 只有在接收到至少 256 个字节后才会开始显示页面。因此,为了确保这些浏览器能正常显示内容,通常需要发送额外的空格字符。
基于上述原因,正确使用这两个函数的顺序应该是:先调用 ob_flush,然后再调用 flush。
当然,在其他 SAPI 环境下,不调用 flush 也是可行的。但为了保证代码在不同环境下的可移植性,建议始终配套使用这两个函数。
<?php
// set_time_limit(0);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// ob_end_flush();
// ini_set('output_buffering', 0);
// ini_set('implicit_flush', 1);
if (ob_get_level() == 0) ob_start();
echo str_repeat(' ' ,4096);
$long = 60;
while($long > 0)
{
$time = date('r');
echo "data: The server time is: {$time}\n\n";
ob_flush();
flush();//break;
sleep(1);
$long --;
}
// var source=new EventSource("http://localhost:18000/sse.php");source.onmessage=function(event){console.info(event.data)};
?>
Nginx 环境下的缓冲处理
如果需要在 Nginx + FPM + PHP 的环境下支持实时输出,需要添加一个特定的响应头。
具体做法是设置 header('X-Accel-Buffering: no')。这将同时消除 proxy_buffering 和(在 nginx >= 1.5.6 版本中)fastcgi_buffering。如果使用 php-fpm,FastCGI 缓冲的关闭至关重要。该头部信息按需设置也更为便捷。相关文档参见 http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_buffering 。
<?php
// set_time_limit(0);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
// ob_end_flush();
// ini_set('output_buffering', 0);
// ini_set('implicit_flush', 1);
// if (ob_get_level() == 0) ob_start();
// echo str_repeat(' ' ,4096);
$long = 60;
while($long > 0)
{
$time = date('r');
echo "data: The server time is: {$time}\n\n";
ob_flush();
flush();//break;
sleep(1);
$long --;
}
// var source=new EventSource("http://localhost:18000/sse.php");source.onmessage=function(event){console.info(event.data)};
?>