How to run WP-CLI command in the background from PHP?
-
I have a long running script in WordPress that creates a report and writes it to an Excel-file, before sending it by email to the user. This project is now complicated enough that I run into timeout issues. I have therefore moved the script into WP-CLI.
I have a button in the WordPress admin panel that fires an AJAX-request to run a function hooked into
wp_ajax_{$action}
. Then I was planning on running the WP-CLI-command withWP_CLI::runcommand()
inside the function called by AJAX. The problem is that WP_CLI is not available at this point. I then tried to useexec
andshell_exec
:exec("wp command_name args");
This works as I want it to, but it blocks the script from continuing, and the browser waits for the AJAX-request to finish. Ok, so I thought I would find a way to run this WP-CLI-command in the background somehow. I have tried everything I could find, but I can’t get it to work.
This runs the command, but PHP hangs and is blocked until the command finishes:
exec("wp command_name args"); exec("wp command_name args > log.txt &"); exec("wp command_name args > NUL &"); exec("wp command_name args > \$null &"); shell_exec("wp command_name args"); shell_exec("wp command_name args > log.txt &"); shell_exec("wp command_name args > NUL &"); shell_exec("wp command_name args > \$null &");
These work for getting the non-blocking functionality I am after, but the command seem to not run at all (I at least get no error messages in the Apache log, and the file the command is supposed to create is never created):
exec("wp command_name args > /dev/null &"); exec("wp command_name args > /dev/null 2>&1 &"); exec("nohup wp command_name args > log.txt &"); exec("wp command_name args > /dev/null 2>/dev/null &"); exec("wp command_name args &> /dev/null &"); shell_exec("wp command_name args > /dev/null &"); shell_exec("wp command_name args > /dev/null 2>&1 &"); shell_exec("nohup wp command_name args > log.txt &"); shell_exec("wp command_name args > /dev/null 2>/dev/null &"); shell_exec("wp command_name args &> /dev/null &");
I can’t for the life of me figure out how to run a WP-CLI command from PHP, but let it run in the background and do its thing without halting PHP execution.
I am on XAMPP for Windows 10 right now for testing, if that matters.
- The topic ‘How to run WP-CLI command in the background from PHP?’ is closed to new replies.