exec()(或类似函数)传回错误输出

时间:2010-08-26 20:14:53

标签: php error-handling exec

我可以传回已执行脚本的输出,但如果脚本出错,我就不会输出错误。

// This is a file that doesn't exists, for testing
$command = './path/to/non/existing/script.sh';

$commandOutput = exec($command, $commandOutput); // works but no error output
//passthru($command, $commandOutput); // works but error output was 127 not file not found
//$commandOutput = escapeshellcmd($command);
echo "The Output:\n|".$commandOutput."|\n";
var_dump($commandOutput);

The Output:

||

我想输出错误消息:

The Output:

|file not found|

如何或者什么功能/参数会这样做?

2 个答案:

答案 0 :(得分:6)

您可以将stderr重定向到stdout,因此exec()等会通过将2>&1附加到您的命令来获取错误消息。

请参阅http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html

答案 1 :(得分:1)

尝试:

ob_start();
passthru($command);
$content_grabbed=ob_get_contents();
ob_end_clean();

echo $content_grabbed;

第二个参数用于发送到系统的命令的返回状态。