cancel
Showing results for 
Search instead for 
Did you mean: 

PHP question - naive or oddball...

decomplexity
Rising Star
Posts: 493
Thanks: 26
Registered: ‎30-07-2007

PHP question - naive or oddball...

I feel I should know the answer to my own question, but...
I have a PHP page which:
-  near the top generates an HTML page (using both PHP and some straight  embedded HTML)
and
- near the bottom does some time-consuming (I/O and CPU time) operations entirely within PHP
Question: does the PHP interpreter wait until PHP operations have concluded on the page (i.e. in my case all the 'bottom bit' has finished) before outputting the HTML or is the HTML output as it is encountered during interpretation?
Zen from May 17. PN Business account from 2004 - 2017
3 REPLIES 3
spraxyt
Resting Legend
Posts: 10,063
Thanks: 674
Fixes: 75
Registered: ‎06-04-2007

Re: PHP question - naive or oddball...

Don't know the definitive answer but I suspect it could be a bit of both depending on the amount of output.
I think output is compressed (gzip, deflate) and sent in chunks so nothing appears until a chunk has been created and sent. If there is only a small amount of output (one chunk) nothing will be sent/appear until "end of file" is recognised.
I doubt that PHP interprets sending the closing </html> tag for the page as a hint to send "end of file" to the browser.
David
Gabe
Grafter
Posts: 767
Registered: ‎29-10-2008

Re: PHP question - naive or oddball...

Not naive. Probably oddball.  Smiley
Assuming we're talking Apache: yes, mod-deflate will add another layer of buffering (default 8k), which could leave your browser waiting for the script, but even if you turn that off (e.g. using
SetEnvIfNoCase Request_URI \.php$ no-gzip dont-vary

in .htaccess), Apache still won't close the connection till after the script has run. Some browsers will show you the html if you flush it to them, others will wait for the connection to close. To close the connection part way through a script, you need to buffer the output using PHP and flush it along with close headers (and a no-encoding header so that Apache doesn't buffer it). E.g., something like:
<?php
ignore_user_abort(true);
ob_start();
echo '<!DOCTYPE html>
<html>
<head>
<title>A Page</title>
</head>
<body>
Some content.
</body>
</html>';
header('Content-Encoding: none');
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
sleep(10);
file_put_contents('log.txt','Log something.');
?>

Gabe
decomplexity
Rising Star
Posts: 493
Thanks: 26
Registered: ‎30-07-2007

Re: PHP question - naive or oddball...

Many thanks Spraxyt and Gabe.
I will experiment with ob_end_flush(). But since my problem is indicative of rubbishly structured code, I will probably end up splitting the 'page outputting' and machine intensive parts and using AJAX for the both (with the first passing data - or at least a 'completion semaphore' - to the second).
Zen from May 17. PN Business account from 2004 - 2017