PHP:为什么exec()不返回输出? [英] PHP: Why isn't exec() returning output?
问题描述
我正在编写一个PHP脚本,用于通过Linux shell命令ping
检查网络连接,并使用PHP的exec()
调用它:
<?php
// Bad IP domain for testing.
$domain_bad = "lksjdflksjdf.com";
$ip_address = $domain_bad;
exec("ping -c 1 $domain_bad", $output, $return_var);
var_dump($return_var);
echo "return_var is: $return_var" . "\n";
var_dump($output);
exit;
?>
我没有从ping $output
中得到错误消息的输出,这是我期望的:
$ php try.php
ping: unknown host lksjdflksjdf.com
int(2)
return_var is: 2
array(0) {
}
如果该域是一个很好的域,例如yahoo.com,则$output
具有ping数组中的输出.但是,如果出现诸如'ping: unknown host lksjdflksjdf.com'
之类的错误,则不会将其返回到$output
数组.
为什么会发生这种情况,并且有更好的方法来做到这一点?
您应将stderr重定向到stdout.
为此,请像这样更改exec()调用:
exec("ping -c 1 $domain_bad 2>&1", $output, $return_var);
有关2>&1
的更多信息,意味着此处. >
I'm writing a PHP script to be used to check for network connections with Linux shell command ping
calling it with PHP's exec()
:
<?php
// Bad IP domain for testing.
$domain_bad = "lksjdflksjdf.com";
$ip_address = $domain_bad;
exec("ping -c 1 $domain_bad", $output, $return_var);
var_dump($return_var);
echo "return_var is: $return_var" . "\n";
var_dump($output);
exit;
?>
I'm not getting the output for the error message from ping in $output
which is what I'm expecting:
$ php try.php
ping: unknown host lksjdflksjdf.com
int(2)
return_var is: 2
array(0) {
}
If the domain is a good domain, such as yahoo.com, then $output
has the output from ping in an array. But if it's an error such as 'ping: unknown host lksjdflksjdf.com'
it doesn't get returned to the $output
array.
Why is this happening and is there a better method to do this?
You should redirect stderr to stdout.
To do that, change your exec() call like this:
exec("ping -c 1 $domain_bad 2>&1", $output, $return_var);
More info about 2>&1
meaning here.
这篇关于PHP:为什么exec()不返回输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!