How can I run a PHP script in the background after a form is submitted?

Doing some experimentation with exec and shell_exec I have uncovered a solution that worked perfectly! I choose to use shell_exec so I can log every notification process that happens (or doesn’t). (shell_exec returns as a string and this was easier than using exec, assigning the output to a variable and then opening a file to write to.)

I’m using the following line to invoke the email script:

shell_exec("/path/to/php /path/to/send_notifications.php '".$post_id."' 'alert' >> /path/to/alert_log/paging.log &");

It is important to notice the & at the end of the command (as pointed out by @netcoder). This UNIX command runs a process in the background.

The extra variables surrounded in single quotes after the path to the script are set as $_SERVER['argv'] variables that I can call within my script.

The email script then outputs to my log file using the >> and will output something like this:

[2011-01-07 11:01:26] Alert Notifications Sent for http://alerts.illinoisstate.edu/2049 (SCRIPT: 38.71 seconds)
[2011-01-07 11:01:34] CRITICAL ERROR: Alert Notifications NOT sent for http://alerts.illinoisstate.edu/2049 (SCRIPT: 23.12 seconds)

Leave a Comment