PHP exec() 不在输出中返回错误消息

2021-12-24 00:00:00 xml exec svn php

我正在尝试以 XML 格式获取 svn 命令的某些输出.当我输入有效参数时,输出正常.但是,当我输入错误的密码时,输出不会显示错误消息.这是 PHP 代码:

I am trying to get certain output for svn command in XML format. Output is ok when I type valid parameters. However, when I type in wrong password, output does not show error message. This is the PHP code:

exec('/usr/bin/svn --username something --password something --non-interactive log -r HEAD --xml --verbose http://a51.unfuddle.com/svn/a51_activecollab/', $output);

这是我在终端中得到的输出:

Here is output I get in the terminal:

<?xml version="1.0"?>
<log>
svn: OPTIONS of 'http://a51.unfuddle.com/svn/a51_activecollab': authorization failed: Could not authenticate to server: rejected Basic challenge (http://a51.unfuddle.com)

这是我从带有 var_dump 的 $output 变量得到的输出:

And here is the output I get from the $output variable with var_dump:

array(2) {
[0]=>
string(21) "<?xml version="1.0"?>"
[1]=>
string(5) "<log>"
}

如您所见,$output 变量不会返回第三行输出,而终端会返回.请帮助我获得与终端相同的输出(我什至尝试使用 shell_exec() 或 system() 方法,但它们返回与 exec() 相同的输出) 如何获得完整输出?提前谢谢你!

As you can see the $output variable does not return third line of output, where terminal does. Please help me to get the same output as I get in terminal (I even tried with shell_exec() or system() methods but they return the same output as exec()) How do I get full output? Thank you in advance!

推荐答案

您也需要捕获 stderr.

stderr 重定向到 stdout 应该可以解决问题.将 2>&1 附加到您的命令末尾.

Redirecting stderr to stdout should do the trick. Append 2>&1 to the end of your command.

例如

exec("/usr/bin/svn --username something --password something --non-interactive log -r HEAD --xml --verbose http://a51.unfuddle.com/svn/a51_activecollab/ 2>&1", $output);

如果它是一个复杂命令(例如一个带有管道的命令,比如做一个 mysqldump 并将它传递给 gzip 然后重定向到文件 mysqldump ... | gzip > db.sql.gz) 创建一个子shell来捕获整个标准错误并将其重定向到标准输出:

If it is a complex command (e.g. one with a pipe, like doing a mysqldump and passing it to gzip and then redirecting to file mysqldump ... | gzip > db.sql.gz) create a subshell to capture the overall standard-error and redirect it to standard-output:

exec('( error_command | cat >/dev/null ) 2>&1', $output)
#     ^                                ^   ^
#     `-- sub-shell with the command --´   `-- stderr to $output

相关文章