Abandon long processes in PHP (but let them end)

I have an HTML form that submits to a PHP page that initiates a script. a script can take anywhere from 3 seconds to 30 seconds to run - the user does not need to be around to complete this script.

Is it possible to initiate a PHP script, immediately print โ€œThank youโ€ to the user (or something else) and let them continue to have fun while your script continues to work?

In my specific case, I submit form data to a php script, which then sends the data to many other locations. Waiting for the success of all posts is currently not in my interest. I just wanted to run a script, let the user go and do whatever they like and what he does.

+4
source share
6 answers

I got the following.

<?php // Ignore User-Requests to Abort ignore_user_abort(true); // Maximum Execution Time In Seconds set_time_limit(30); header("Content-Length: 0"); flush(); /* Loooooooong process */ ?> 
0
source

Put your long term work in another php script like

background.php:

 sleep(10); file_put_contents('foo.txt',mktime()); 

foreground.php

 $unused_but_required = array(); proc_close(proc_open ("php background.php &", array(), $unused_but_required)); echo("Done); 

You will immediately see โ€œFinishโ€ and the file will be written in 10 seconds.

I think proc_close works because we give proc_open no pipes and no file descriptors.

+2
source

In the script you can set:

 <?php ignore_user_abort(true); 

Thus, the script will not be completed when the user leaves the page. However, be very careful when combining this whith

  set_time_limit(0); 

Since then, the script can run forever.

+1
source

You can use set_time_limit and ignore_user_abort , but, generally speaking, I would recommend that you queue the task and use an asynchronous script to process it. This is a much more solid and sturdy construction.

+1
source

You can try flush and its associated output buffer functions to immediately send everything in the buffer to the browser:

0
source

Theres an API wrapper around pcntl_fork () called php_fork .

But also this question was at the Daily WTF ... do not prick a nail with a glass bottle.

0
source

All Articles