Yes.
This can easily be done without asynchronous processing if you use the HTTP headers correctly.
Under normal circumstances, PHP will stop processing as soon as the client at the other end closes the connection. If you want to continue processing after this event, you need to do one thing: tell PHP to ignore user interrupts. How?
ignore_user_abort()
This will allow your script device to continue to work even after the client receives the dash line. But we also face the problem of how to inform the client that the request he completed has been completed in order to close the connection. Typically, PHP transparently handles sending these headers for us, unless we specify them. Here, however, we need to do this explicitly or the client will not know when we want them to stop reading the answer.
To do this, we must send the appropriate HTTP headers to tell the client when to close:
Connection: close Content-Length: 42
This combination of headers tells the client that after it reads 42 bytes of the body response, the message is complete and that they should close the connection. There are several consequences to this method:
- You have to generate your answer BEFORE sending any output, because you need to determine its size of the length of the content in bytes so that you can send the correct header.
- You must send these headers before you echo the call.
So your script might look something like this:
<?php ignore_user_abort(); // do work to determine the response you want to send ($responseBody) $contentLength = strlen($responseBody); header('Connection: close'); header("Content-Length: $contentLength"); flush(); echo $responseBody; // --- client will now disconnect and you can continue processing here ---
The big "gotchya" with this method is that when you run PHP in web-based SAPI, you can easily overcome the maximum time directive if you are involved in labor-intensive processing after the end-user client closes the connection. If this is a problem, you may need to consider asynchronous processing using cron, because there is no time limit when PHP runs in the CLI environment. Alternatively, you can simply limit the time of your scripts in a web environment using set_time_limit docs .
It is worth noting that if you do something like this, you can also add a check to connection_aborted() docs when generating your response organ, so that you can avoid additional processing if the user interrupted before the transfer was completed.