Kudos
Collect
Twiiter
Facebook
Share
Develop somethings, meditation, reading and thinking...

PHP Flush

Last updated over 4 years ago
0 0 0 0

PHP Flushing

PHP 에서 Flush 를 쓰는 이유는 여러가지가 있겠지만, 개인적으로 브라우저에서 Timeout 이 나지 않게하기 위한 목적으로 자주 쓴다. 서버에서는 계산을 하고 있는데 브라우저에 아무것도 표시되지 않아 접속이 종료되게 되면 곤란한 경우가 있기 때문이다.

오래간만에 Timeout 방지를 위해 프로그램을 작성하던 중 제대로 작동하지 않아 살펴보았다. 아래와 같은 예제코드로 테스트해 볼 수 있다.

ob_end_flush();
ob_implicit_flush();
for ( $i = 0; $i < 10; $i++ ) {
    echo "$in";
    echo str_pad('',1024*64)."n";    
    sleep(1);
}
exit;

// alternatively
ob_end_flush(); // This code should be called at start. Like a cmd screen.
for ( $i=1; $i <= 10; $i++ ) {
    echo "{$i} sending...";
    flush(); // Push the new data to the browser. Like a cmd screen.
    sleep(1);
    echo " ok<br>";
    echo str_pad('',1024*64)."n";    
    flush(); // Push the new data to the browser. Like a cmd screen.
}
echo "TEST...";

이렇게 하면 한줄한줄 화면에 표시 되어야 하는데, 아무리 테스트를 해도 처리가 끝난 후 한번에 표시가 된다. 서버의 처리속도 향상을 위해 서버의 gzip 옵션을 켜 둔게 문제였다. 아래 부분을 확인하고 On 되어 있으면 Off. str_pad1024*64 는 서버 환경에딸 적절하게 조정한다.

output_buffering = Off
zlib.output_compression = Off
gzip  off;
proxy_buffering  off;

Nginx 의 경우 nginx.conf 파일에서 지정하면 모든 설정에 반영이 되므로, nginx.conf 에서 gzip on 으로 설정하고, 필요한 서비스에서만 개별적으로 off 설정을 하면 되겠다.

References

https://stackoverflow.com/questions/3133209/how-to-flush-output-after-each-echo-call/4978809#4978809

Hi, my name is Richard. I’m a developer wants to make the world better with logic power. Mainly I use Linux, Nginx, MySQL, PHP and JavaScript . I want to share my knowledge with someone that it was also based from some great persons via LYNMP. 👨‍💻

Essedrop - Make your file online instantly
 

Responses

Leave a response to @richard

Please sign in to comment.
Markdown is also available in comment.