Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling ob_flush() and flush(), yet browser doesn't show any output until script finishes

Hi Please View Below Code :

<?php
ob_start();

echo "Start ...<br />\n";
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo "$i<br />\n";
    ob_flush(); 
    flush();
    sleep(1);
}
echo "End ...<br />\n";
?>

It's Incorrect ? i'm tested it but my output show when script is done, have any solution ?

like image 329
DJafari Avatar asked Apr 24 '11 13:04

DJafari


3 Answers

Hey man I was also got stuck in this problem and finally got the correct solution here it is for you

you have to add content type for your page you can do that by two ways 1. using html tag

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Ex.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wp Migration</title>
</head>
<body>
<?php 
for($i=0;$i<70;$i++)
{
echo 'printing...<br>';
ob_flush();
flush();
sleep(3);
}
?>
</body>
</html>
  1. using php header function

    <?php header( 'Content-type: text/html; charset=utf-8' ); ?>

Ex.

<?php 
header( 'Content-type: text/html; charset=utf-8' );
for($i=0;$i<70;$i++)
{
echo 'printing...<br>';
ob_flush();
flush();
sleep(3);
}
?>

All the best

like image 77
Rahul Shinde Avatar answered Oct 16 '22 20:10

Rahul Shinde


Some browsers need to receive at least 256 characters before they start to render. Have you already tried to stuff more output like:

echo str_repeat('&nbsp;', 50) . "$i<br />\n";

EDIT:

Under Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 I was able to reproduce the problem of the OP by setting

zlib.output_compression = On

Turning it off again by

zlib.output_compression = Off

made the script work as wanted.

like image 27
Jürgen Thelen Avatar answered Oct 16 '22 20:10

Jürgen Thelen


Try removing the call to ob_start() on your first line : there is no need for you to enable output buffering -- and it probably causes troubles, here.


I've tested your code :

  • If ob_start() is called on the first line, I only see the output when the script finishes, after 10 seconds
  • If I remove that call to ob_start(), then, I see one line of output every second, as soon as it's displayed on the standard output.
like image 4
Pascal MARTIN Avatar answered Oct 16 '22 21:10

Pascal MARTIN