Exec()之后的PHP StdErr [英] PHP StdErr after Exec()
问题描述
在PHP中,我正在使用exec()执行命令,如果成功则返回URL;
In PHP I am executing a command with exec(), and it returns if successful an URL;
$url = exec('report');
但是,如果出现问题,我想检查stderr.我将如何阅读信息流? 我想使用php://stderr,但是我不确定如何使用它.
However, I want to check stderr, if something went wrong. How would I read the stream? I want to use php://stderr, but I am not sure how to use it.
推荐答案
如果要执行命令,并同时获取stderr
和stdout
,而不是合并",则解决方案可能使用 proc_open
,它可以很好地控制正在执行的命令- -包括管道stdin
/stdout
/stderr
的方法.
If you want to execute a command, and get both stderr
and stdout
, not "merged", a solution would probably to use proc_open
, which provides a great level of control over the command that's being executed -- including a way to pipe stdin
/stdout
/stderr
.
这是一个示例:让我们考虑在test.sh
中有这个shell脚本,它同时写入stderr
和stdout
:
And here is an example : let's consider we have this shell-script, in test.sh
, which writes to both stderr
and stdout
:
#!/bin/bash
echo 'this is on stdout';
echo 'this is on stdout too';
echo 'this is on stderr' >&2;
echo 'this is on stderr too' >&2;
现在,让我们在temp.php
中编写一些PHP的代码-首先,我们初始化i/o描述符:
Now, let's code some PHP, in temp.php
-- first, we initialize the i/o descriptors :
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w"), // stderr
);
然后,使用这些描述符在当前目录中执行test.sh
命令,并说输入/输出应该为/c至$pipes
:
And, then, execute the test.sh
command, using those descriptors, in the current directory, and saying the i/o should be from/to $pipes
:
$process = proc_open('./test.sh', $descriptorspec, $pipes, dirname(__FILE__), null);
我们现在可以从两个输出管道中读取内容:
We can now read from the two output pipes :
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
并且,如果我们输出这两个变量的内容:
And, if we output the content of those two variables :
echo "stdout : \n";
var_dump($stdout);
echo "stderr :\n";
var_dump($stderr);
执行temp.php
脚本时,我们得到以下输出:
We get the following output when executing the temp.php
script :
$ php ./temp.php
stdout :
string(40) "this is on stdout
this is on stdout too
"
stderr :
string(40) "this is on stderr
this is on stderr too
"
这篇关于Exec()之后的PHP StdErr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!