omega1
omega1

Reputation: 1052

How sleep() works in PHP

Please excuse what may seem like a very simple question and may lack of understanding of how PHP/sleep() works, but I was after some guidance on the following code:

<?php
$time_now = time();
echo "Time Now : " . $time_now;
sleep(10);
$time_then = time();
echo "<br>Time Then : " . $time_then;
?>

I was expecting this code to output the current time, then wait 10 seconds, then output the time 10 seconds later.

Instead it waits the 10 seconds set and outputs both the times at the same time. The times ARE correct in that the 'Time Now' is when I executed the code, and the 'Time Then' is 10 seconds later, but it does not respond how I expected (output Time Now, wait 10 seconds, then continue to execute the code and show 'Time Then').

Given that my understanding is clearly incorrect, is it possible to achieve this? Or would I be better to trigger another file to load what I want to do as follows:

File 1

<?php
$time_now = time();
echo "Time Now : " . $time_now;
header('Location: page2.php');
?>

File 2

<?php
sleep(10);
$time_then = time();
echo "<br>Time Then : " . $time_then;
?>

Thank you.

Upvotes: 2

Views: 2107

Answers (2)

techblu3
techblu3

Reputation: 170

If you run it on server it will indeed give the output after the script finished.

But if used as a command line script it will output then sleep for ten seconds and then continue

In @lolka_bolka mentioned if you want value then and there you can use flush

Upvotes: 1

vaso123
vaso123

Reputation: 12391

You need to use the flush function of PHP, to get the excepted result.

PHP gives you the output, when script has finished. If you want to show the result in real time, you need to flush the output buffer.

$time_now = time();
echo "Time Now : " . $time_now;
flush();
sleep(10);
$time_then = time();
echo "<br>Time Then : " . $time_then;

Upvotes: 6

Related Questions