简体   繁体   中英

How can I run a php process in the background?

I would like to run a php script in the background as it takes much time and I don't want to wait for it.

This question relates to:

php execute a background process

I tried to make this work on my linux centos machine, but unfortunately it seems not to be working.

This is my code:

$cmd = 'php '.realpath($_SERVER["DOCUMENT_ROOT"]).'/test/sample.php';

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
exec(sprintf("$s > $s 2>&1 & echo $1", $cmd, $outputfile),$pidArr); 

sleep(2);

print_r($outputfile);
print_r($pidfile);

I included the sleep(2) to make sure the sample.php script is finished. The sample.php only contains echo 'Hello world'; I tried both exec options, but none of them worked. The above script doesn't show any output.

I tried to run the same $cmd in linux command line and it showed me the output from sample.php script.

I would like to make this run first, but in addition I would like to send variables to the sample.php script as well.

Your help is very appreciated.

You can use set_time_limit(0) to allow script to run indefinitely and ignore_user_abort() to keep running script in background, even if the browser of tab have been closed. This way if you redirect your browser to somewhere else, script will keep running in background.

This approach to running php scripts in the background seems a bit awkward. And depending on if you pass additional parameters based on user input, could also create a scenario where an attacker could inject additional commands.

For use cases like this, you could be using cron, if you don't need a response immediately, or a job manager like Gearman , where you can use a Gearman server to manage the communication between the we request and the background job.

I made some adjustments

$cmd = 'php '.realpath($_SERVER["DOCUMENT_ROOT"]).'/test/sample.php';
$outputfile = 'ouput.txt';
$pidfile = 'pid.txt';
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
exec(sprintf("$s > $s 2>&1 & echo $1", $cmd, $outputfile),$pidArr); 

sleep(2);

print_r(file_get_contents($outputfile));
print_r(file_get_contents($pidfile));

Not sure if you defined the variables before. I tested it on Windows and it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM