Executing command line from PHP
Use shell_exec() or exec(). shell_exec() is typically more useful, because it returns all of the output, whereas exec() only retuns a single line.
Check shell_exec() exists
You can find its been disabled in php.ini for instance.
if(!function_exists('shell_exec'))
echo('shell_exec() is not available. Please check your PHP configuration.');
Running a script with shell_exec()
exec("/usr/bin/python3 $PathToScript $ProcessArguments" . " 2>&1", $Output, $Status); //The " 2>&1" part captures any error messages and puts them in the $Output array as well
if ($Status === 0)
{
//----- SUCCESS -----
echo "Output from Python script:<br>";
foreach ($Output as $Line)
{
echo($Line . "<br>);
}
}
//----- AN ERROR OCCURED -----
echo "Error executing script ($Status).<br>";
foreach ($Output as $Line)
{
echo($Line . "<br>);
}
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.