Does PHP send over code as it processes the file, or does it compose the whole HTML response and then send it over? For example would it make any difference to move expensive PHP functions into the file footer on the server?
Also, would it make any difference if you were using Transfer-Encoding: chunked?
Ultimately, it depends. Most PHP hosting mechanisms I have used will stream the response in chunks, as it is received from the script, omitting the
Content-Lengthheader entirely (since this is not known in advance). You can flush the response usingflush()periodically to force the server to transmit what it has buffered so far to the client.So, if you are going to be doing things that take a lot of time and want to allow the page to render in advance, the proper way to do this would be to output as much of the page as possible, call
flush(), and then do your expensive tasks. Just be sure not to take longer than the declared maximum PHP script duration.Okay, so that explanation is admittedly a bit oversimplified:
The
Content-Lengthheader may actually be sent under some circumstances. For example, if the script’s response is less than PHP’s buffer for sent data, and/or if the script takes under a certain amount of time to execute, then the server will know exactly how long the content is and can add the length header.Further,
flush()may not actually do anything. This depends on your server configuration and other factors. Note specifically these warnings in the documentation regarding server-side behavior:In other words: test, test, test. Make sure that the web server isn’t interfering with the behavior you’re trying to achieve. Reconfigure the web server if necessary.