实时输出如果放在js中我们可以直接使用settimeout来守时输入很方便,但是如果在php中实现起来就不能这样了,下面我来给介绍利用 ob_flush() 和 flush()函数实现即时实时输出内容.
一般情况下,PHP都是将整个页面全部执行完成后,才会把要输出的内容发送回客户端,例如如下代码:
for ($i = 0; $i < 10; $i++) { echo $i; sleep(1); }
这段代码会在10秒钟后一次性输出"0123456789",对于运行时间较长的PHP程序来说可能都需要即时输出内容来查看运行情况,代码如下:
header("Content-type:text/html;charset=utf-8"); //设置执行时间不限时,代码如下: set_time_limit(0); //清除并关闭缓冲,输出到浏览器之前使用这个函数,代码如下: ob_end_clean(); //控制隐式缓冲泻出,默认off,打开时,对每个 print/echo 或者输出命令的结果都发送到浏览器,代码如下: ob_implicit_flush(1);
这就用到了PHP的输出控制函数ob_flush()和flush(),我们把代码修改成下面这样,代码如下:
<?php $str = "Hello world"; echo $str.str_repeat(' ', 256); ob_flush(); flush(); sleep(10); echo $str; ?>
这段代码则会马上在屏幕上打印 Hello world,关键就在于第2和第3行调用的两个函数 ob_flush() 和 flush(),这两个函数得一起使用才能保证页面马上输出Hello world,其中str_repeat(' ', 256)则是为了解决某些浏览器必须在接收到256个字符后才会显示内容.
对上面函数升级,代码如下:
<?php error_reporting(0); set_time_limit(0); $buffer = ini_get('output_buffering'); echo str_repeat(' ',$buffer+1); ob_end_flush(); for($i=1;$i<100;$i++){ echo "$i<br>"; sleep(1); flush(); } ?>
这样,页面就会每一秒输出一个数字,我们可以很方便的使用PHP的输出控制来实现页面执行进度的显示,不过,由于PHP页面有执行时间限制,而且长时间执行一个页面会对服务器造成一定的压力.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)