Skip to content

Instantly share code, notes, and snippets.

@benrolfe
Last active December 16, 2015 20:48
Show Gist options
  • Save benrolfe/5494728 to your computer and use it in GitHub Desktop.
Save benrolfe/5494728 to your computer and use it in GitHub Desktop.
We've been working on a project recently where we wanted to run a background CLI script that gets fired from PHP. For example, a user presses a button on your frontend interface that fires off a PHP script that runs in the background for a while. The user can then continue using the site, rather than waiting for the script to finish. You’ll need…
function run_background_process( $file )
{
if ( is_windows() )
{
// create command object
$objShell = new COM( 'WScript.Shell' );
// run windows command
$objShell->Run(
$strCommand = sprintf( 'php %s.php', $file ),
$intWindowStyle = 7, // the active window remains active.
$bWaitOnReturn = FALSE
);
}
else
{
// run command, and continue ('-q' requires output to be /dev/null)
$cmd = sprintf( 'nohup php -q %s.php > /dev/null 2>&1 &', $file );
// run exec function
$result = exec( $cmd, $output, $return_status );
// popen and pclose also works
#pclose( popen( $cmd, 'r' ) );
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment