PHP: sleep () for a specific line of code

Is it possible to use the sleep () function (or some other function) to wait before execution?

I have for example:

<div>bla bla</div> <?php $a echo $a; ?> some divs and html <?php $b echo $b; ?> 

How to execute the first php script 5 seconds after the page loads, but to show everything else as the page loads? If I use sleep () before the first php, it delays loading the whole page.

+5
source share
3 answers

You want to use AJAX for this. An example of using jQuery:

 <div id="content"> <-- You want to load something here after 5 seconds --> </div> <script type="text/javascript"> setTimeout(function() { $('#content').load("/url/to/your/script.php"); }, 5000); // 5000 is the time to wait (ms) -> 5 seconds </script> 

This will load the output ( echo ) of the script.php into a div with the identifier "content". By doing this this way, you allow the client to do all the rendering work, as @GhostGambler already recommended

This will not block the output of other content sent by the initial script.

+2
source

Yes, you can use sleep() to delay execution, but since the output is usually buffered and not sent to the browser until the script completes the result, you will not do what you need.

If you call flush() and ob_flush() immediately after calling sleep() , the output buffer is cleared and sent to the browser.

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

+3
source

The HTTP protocol includes a special Transfer-Encoding header, which allows you to indicate that the page can be loaded into chunks ( Transfer-Encoding: chunked ), although there is no guarantee that the browser will do this (but most browsers).

The Transfer-Encoding: chunked header tells the browser that the web server does not know Content-Length in advance.

Although you usually want to use Ajax to load content after this page is fully loaded, you can use this technique to display, for example, terminal output in real time, without the need for JavaScript.

See this question on how to implement chunked answers in PHP.

0
source

Source: https://habr.com/ru/post/1258136/


All Articles