PHP flush 函数使用注意事项

yipeiwu_com5年前PHP代码库

ob_*系列函数, 是操作PHP本身的输出缓冲区.

所以, ob_flush是刷新PHP自身的缓冲区.

而flush, 严格来讲, 这个只有在PHP做为apache的Module(handler或者filter)安装的时候, 才有实际作用.
它是刷新WebServer(可以认为特指apache)的缓冲区.

在apache module的sapi下, flush会通过调用sapi_module的flush成员函数指针,
间接的调用apache的api: ap_rflush刷新apache的输出缓冲区, 当然手册中也说了, 有一些apache的其他模块,
可能会改变这个动作的结果..

有些Apache的模块,比如mod_gzip,可能自己进行输出缓存,这将导致flush()函数产生的结果不会立即被发送到客户端浏览器。

甚至浏览器也会在显示之前,缓存接收到的内容。例如 Netscape浏览器会在接受到换行或 html标记的开头之前缓存内容,并且在接受到 标记之前,不会显示出整个表格。

一些版本的 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 + fpm + php 上支持需要加一个响应头

header('X-Accel-Buffering: no');
This eliminates both proxy_buffering and (if you have nginx >= 1.5.6), fastcgi_buffering. The fastcgi bit is crucial if you're using php-fpm. The header is also far more convenient to do on an as-needed basis.
Docs on X-Accel-Buffering 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)};
?> 

相关文章

PHP单元测试PHPUnit简单用法示例

本文实例讲述了PHP单元测试PHPUnit简单用法。分享给大家供大家参考,具体如下: windows开发环境下,PHP使用单元测试可以使用PHPUnit。 安装 首先下载PHPUnit,...

php实现简易聊天室应用代码

php实现简易聊天室应用代码

核心逻辑 在定义应用程序的核心功能之前,先来看一看聊天应用程序的基本外观,如以下截图所示: 通过聊天窗口底部的输入框输入聊天文本。点击Send按钮,就开始执行函数set_chat_ms...

php定时计划任务的实现方法详解

我在uchome 中 分析到, uchome是这样做的1. 把所有的计划任务存放到数据库2. 每次用户进行操作或打开页面的时候都按排序执行一条计划任务. 也就是轮番判断,时间到了的, 就...

php使用function_exists判断函数可用的方法

本文实例讲述了php使用function_exists判断函数可用的方法。分享给大家供大家参考。具体如下: 本文所述的函数用来建立一张 gif 格式图形,参数 im 为使用 imagec...

浅析Yii中使用RBAC的完全指南(用户角色权限控制)

写在前面    * 我的feed地址已经修改为: http://feeds.imdong.net ,请更新您的阅读器。   ...