How to run wp-cli command in the background from php?

Member

by jasen , in category: PHP General , a year ago

How to run wp-cli command in the background from php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a year ago

@jasen 

To run a wp-cli command in the background from PHP, you can use the exec function or the shell_exec function. Here's an example using exec:

1
2
3
4
<?php
$command = '/path/to/wp-cli-command > /dev/null 2>&1 &';
exec($command);
?>


This example demonstrates running the wp-cli command in the background by redirecting its output to /dev/null and appending & at the end of the command.


Note that /path/to/wp-cli-command should be replaced with the actual path to your wp-cli command. Also, the > /dev/null 2>&1 & part is used to redirect the output and errors to the null device and run the command in the background, respectively.


You can also use shell_exec instead of exec if you want to capture the output of the command:

1
2
3
4
<?php
$command = '/path/to/wp-cli-command > /dev/null 2>&1 &';
$output = shell_exec($command);
?>


In this case, $output will contain the output of the command, if there is any.


Make sure to configure the server properly to allow the execution of the wp-cli command from PHP and use the correct path to the command.