Matt Pfeffer Matt Pfeffer - 6 months ago 9
PHP Question

How to keep executing php script while disconnecting user?

I am looking to have the user submit some information from a form to a page. But I want to do some other stuff after getting the info but I don't want to have the user wait around.
Is there a way to have the user think that the page has finished while still having PHP execute the script?

Answer

That is certainly doable. You can use ob_flush() to continue the session. I have an example snippet here: https://snippetbox.xyz/9eb54a2a1f52dc1f5d38/

Pulled from that URL:

This will disconnect the user while the script is still processing

<?php
 ob_end_clean();
 header("Connection: close");
 ignore_user_abort(); // optional
 ob_start();
 echo ('Text the user will see');
 $size = ob_get_length();
 header("Content-Length: $size");
 ob_end_flush(); // Strange behaviour, will not work
 flush();            // Unless both are called !
 session_write_close(); // Added a line suggested in the comment
 // Do processing here
 sleep(30);
 echo('Text user will never see');
?>
Comments