0

So I need a little help, is there a better way to have php wait before executing the next line of code?

I tried:

$response = $_POST[response];
echo "</br>".$response;
if (strpos($response,'no') !== false) {
    sleep(2);
    echo "</br>";
    echo 'Why not?';
}

But this method does not display the

echo "</br>".$response;

before it sleeps. It sleeps for the 2 seconds, then displays the response.

How can I get it to echo $response, then wait 2 seconds before is says "Why Not"

Thank you in advance.

user1789437
  • 490
  • 1
  • 7
  • 22

3 Answers3

2

Flush your buffer (UPDATE):

<?
$response = $_POST[response];
echo "</br>".$response;
ob_end_flush();
flush();
if (strpos($response,'no') !== false) {
    sleep(2);
    echo "</br>";
    echo 'Why not?';
}
?>

References: http://php.net/manual/en/function.ob-flush.php, http://php.net/flush

Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63
1

You have to use flush the buffer content to see the results

@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
ob_start();
$response = $_POST[response];
echo "<br />".$response;
ob_flush(); 
flush();
if (strpos($response,'no') !== false) {
    sleep(2);
    echo "<br />";
    echo 'Why not?';
}

I am using both ob_flush() and flush() as stated in http://php.net/manual/en/function.flush.php but just see what works. Sometimes only using flush() also works, depending on the server config.

Be aware of gzip/deflate. You can't deflate an output stream and in the middle of it output the buffer. You can either turn it off by using the htaccess or with the 2 first lines of the code

Sanne
  • 1,116
  • 11
  • 17
0

It looks like the output buffer isn't being flushed before the sleep call. You can indeed control this manually as Pentium10 Points out: https://stackoverflow.com/a/3078873/1461223

Community
  • 1
  • 1
Osmium USA
  • 1,751
  • 19
  • 37