Dynamo

JDW

2 Jun 2015, 3:15 am

PHP script execution & sleep()

I’m in the midst of learning PHP right now, so please be gentle with me! :-)

It seems that the entire PHP script must execute before something is presented to the browser. For example:

    <?php
    echo "Start...<br>";
    usleep(4E6); //sleep for 4 seconds
    echo "Done";
    ?>

If I save the above to a *.php file, upload it to my server and display it in-browser, the browser window is blank for 4 seconds and then the following is displayed all at once:

Start...
Done

Is it possible to write a PHP script such that “Start…” is written to the browser, then the 4 second delay takes place, and then the text “Done” is written to the same browser window, beneath “Start…”?

Thank you,

James Wages

waltd

2 Jun 2015, 11:10 am

It is possible to stream part of the page to the browser, followed by more later. Look in the section of the PHP manual on the flush() method. Note carefully that this relies on the web server (apache in your case) to support this feature and to not override it with its own built-in schemes, such as gzip encoding. You may need to tinker with those settings in order to get the effect, but the gzip encoding is there to make every request faster and less expensive bandwidth-wise, so this may be a false economy. If you want this sort of effect visually (loading part immediately to sate the impatient visitor, and loading the time-consuming stuff later as it completes) then you may want to switch to using JavaScript callbacks to call the long-running part after the main page has loaded.

Walter

On Jun 1, 2015, at 11:15 PM, JDW <[email protected]> wrote:

I’m in the midst of learning PHP right now, so please be gentle with me! :-)

It seems that the entire PHP script must execute before something is presented to the browser. For example:

<?php
>    echo "Start...<br>";
>    usleep(4E6); //sleep for 4 seconds
>    echo "Done";
> ?>

If I save the above to a *.php file, upload it to my server and display it in-browser, the browser window is blank for 4 seconds and then the following is displayed all at once:

Start...
Done

Is it possible to write a PHP script such that “Start…” is written to the browser, then the 4 second delay takes place, and then the text “Done” is written to the same browser window, beneath “Start…”?

Thank you,

James Wages

Freeway user since 1997

http://www.walterdavisstudio.com