search
HomeBackend DevelopmentPHP Tutorialflush()函数有时好像不起作用

下面这个程序是我在网上找的,他注释中说第一句非常关键,可我发觉第一句根本没起作用,没有输出300个空格。而且我把第一句删了运行结果完全相同,这是为什么啊
for($i = 1; $i  // 这一句话非常关键,cache的结构使得它的内容只有达到一定的大小才能从浏览器里输出
// 换言之,如果cache的内容不达到一定的大小,它是不会在程序执行完毕前输出的。经
// 过测试,我发现这个大小的底限是256个字符长。这意味着cache以后接收的内容都会
// 源源不断的被发送出去。
For($j = 1; $j  echo $j." ";
flush(); //这一部会使cache新增的内容被挤出去,显示到浏览器上
sleep(1); //让程序"睡"一秒钟,会让你把效果看得更清楚
}
?>

我自己写了个程序,我发现把ob_flush()改成flush()后,第一条就不输出了,我记得flush()是立即输出缓冲区的内容啊,为什么不输出呢。
ob_end_flush();好像和ASP中的response.end也不同哦,ob_end_flush();后,后面的内容仍然会输出啊,有什么办法让后面的内容停止输出不


 
ob_start();
echo "第一条";
ob_flush() ; //立刻输出缓冲区中的内容
echo "第二条";
ob_get_clean() ; //清除缓冲区中的内容
echo "第三条" ;
ob_end_flush();
?>


回复讨论(解决方案)

只有 IE 才有缓冲区装满或传输结束才解释传入的内容的现象
空格不是 HTML 元素,无论多少个,也只会显示一个

flush() 的作用是将 php 系统缓冲区的内容推出到客户
ob_flush() 的作用是将 php 用户缓冲区的内容推出到 php 系统缓冲区
ob_end_flush() 的作用是将 php 用户缓冲区的内容推出到 php 系统缓冲区,并关闭 php 用户缓冲区
ob_end_clean() 的作用是将 php 用户缓冲区的内容清空,并关闭 php 用户缓冲区

response 采用的是完全不同的机制(response 是设备)
只有在 ob_start() 后的 ob_end_clean() 才相当于 response.end

我还是不太明白 系统缓冲区 和用户缓冲区,在网上也搜索不到这方面的资料,只是说PHP 支持多级缓冲区。好像是说可以建立n级缓冲区,我想是不是在缓冲区里又可以建缓冲区。这方面PHP比ASP复杂。

系统缓冲区 是指php的输出缓冲区,可用 output_buffering 控制其大小
每当 php 程序有输出时将存放在里边,待装满了或程序结束时一次性发送给用户
flush() 就是强制输出他里面的内容

用户缓冲区 是指用 ob_start() 开辟的缓冲区,每个 ob_start() 就是一个,允许嵌套

你试下这段代码,我在ie,firefox,chrome下都没问题。

<?phpecho str_pad('',4096);set_time_limit(50);for($i=0;$i<=5;$i++){    echo $i.'<br />';ob_flush();flush(); sleep(1);}?>

关于服务器端推送数据客户端即时显示的问题,其实是会受到web服务器,浏览器,以及代码三个方面的影响。

你要先明白整个流程:
web服务器也有缓冲区buffer,这个buffer的大小,会关系到服务器字节数到达多少后再推送给客户端浏览器。
然后浏览器也会有个buffer,收到多少字节后才显示出来。
你那段代码只是填充一些空白来欺骗浏览器让浏览器把内容即时显示出来。而问题可能在服务器端那边,根本没把数据发到客户端来。

对于服务器如何设置,apache貌似默认设置就可以。
nginx需要关闭gzip,然后设置fastcgi_buffers,fastcgi_buffer_size等值才行。具体你自己再查一下吧。

另外不同浏览器对于缓冲区buffer的规定也不一样,要想实现多种浏览器支持,你就尽量填大一些吧。

iis magager - system.webServer/handlers responseBufferLimit设为0, 
php.ini - output_buffer =Off

for($i = 1; $i 

飘过 只看版主的回答 打个记号

你试下这段代码,我在ie,firefox,chrome下都没问题。

<?phpecho str_pad('',4096);set_time_limit(50);for($i=0;$i<=5;$i++){    echo $i.'<br />';ob_flush();flush(); sleep(1);}?>
 感谢。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools