Execute a console command in PHP revised

While it seems like there are multitude of different methods to execute commands in PHP, so far the code I will go over below is my preferred method. Using the passthru() function works nicely and includes the final return code of whatever was being executed, which is generally useful to me in error checking. In processing, I also include ob_start(), ob_get_contents(), and ob_end_clean() so that I can capture the console programs output and return it the user eventually.

//execute a console command and return both the commands 
//success value and any output to the console it made
function executeConsoleCommand($commandToExecute, &$commandConsoleOutputToAppend)
{
	$returnValue = 0;

	$commandConsoleOutputToAppend .= $commandToExecute . "\r\n";

	//catch console output
	ob_start();

	//execute the console program
	passthru($commandToExecute, $returnValue);

	//save console output to a string variable 
	//(this should APPEND to the variable)
	$commandConsoleOutputToAppend .= ob_get_contents() . "\r\n";
	ob_end_clean();

	//add this data to the log file
	updateLogFile($commandConsoleOutputToAppend, "a");
	
	return $returnValue;
}

Take note that in my function, I append all of the console output to a parameter variable using pass by reference. The console program’s return code is passed back through the standard return variable of the function.

This entry was posted in General and tagged , , , , , . Bookmark the permalink.