How to get real-time output from php as it happens ? without storing all in memory/buffer and echoing all at once to the browser ?
if i create a realtime-echo.php
<?php
for($i = 0; $i < 10; $i++)
{
echo $i;
sleep(1);
}
and access it from Internet browser it gives following output , after 9-10 seconds.
0123456789
but what i am willing the output to be is, when i access the php file from my browser it should give
0
then wait 1 second then add "1" after the "0" then wait 1 second then add "2" after the "1" and so on.
idk what its called like animation/real-time .
How do achieve this ?
I am working on the project where i need the constant output as it happens so i can keep eye on whats happening and where its going.
Thanks
PHP is an interpreted server language. Using PHP you can create some local programs or implement the server-side of a web application. If you run your PHP code in command-line, then your code should work as expected. However, if you use your PHP through the browser, then there is a request-response policy applicable at HTTP. If you send a request to the browser, then you will only receive the response of the server when the script was executed. So, you request the page through a browser and then wait for the response. The server receives the request and echoes out ten numbers with a second sleep between them. After the server finishes its job it sends the response back to your browser which will get the ten numbers in a single batch. This is why you are experiencing that you wait for ten seconds and then all the output is displayed at once: It is because the server executed the sleeps and collected your echoes and then sent them back to your browser which was just displaying it.
Of course, if you want to display ten server responses in your browser then you will have to do better. Maybe you can use polling (using the
setInterval
or thesetTimeout
function of Javascript you are waiting the seconds in your client-side and send the post requests after that to the server using$.ajax
, for instance. At the server you handle the request and respond with the correct output. Your client-side should have a callback where you handle the response of the server and displays it accordingly).Output buffering may be turned on which prevents realtime output. So you need an
echo
in combination withflush()
andob_flush()
.Source: http://php.net/manual/en/function.ob-flush.php#109314
I tried to create a fiddle but
sleep()
was not allowed in a fiddle. So I created a GIF.Use
flush()
function when you want the current output to be displayed.A quick example:
If you are using output buffering, you also need to call
ob_flush()
Note: Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
Something like this:
Working example (without
ob_start()
function):