这里有新鲜出炉的 PHP 教程,程序狗速度看过来!
PHP(外文名: Hypertext Preprocessor,中文名:"超文本预处理器")是一种通用开源脚本语言。语法吸收了 C 语言、Java 和 Perl 的特点,入门门槛较低,易于学习,使用广泛,主要适用于 web 开发领域。PHP 的文件后缀名为 php。
ob_flush/flush 在手册中的描述, 都是刷新输出缓冲区, 并且还需要配套使用, 所以会导致很多人迷惑… 其实, 他们俩的操作对象不同, 有些情况下, flush 根本不做什么事情
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)};
- ?>
来源: http://www.phperz.com/article/17/0802/342925.html