PHP:为什么 exec() 不返回输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16665041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:31:23  来源:igfitidea点击:

PHP: Why isn't exec() returning output?

phpexecping

提问by Edward

I'm writing a PHP script to be used to check for network connections with Linux shell command pingcalling it with PHP's exec():

我正在编写一个 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;
?>

I'm not getting the output for the error message from ping in $outputwhich is what I'm expecting:

我没有从 ping 中获得错误消息的输出,$output这正是我所期望的:

$ 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 $outputhas 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 $outputarray.

如果该域是一个好的域,例如 yahoo.com,则$outputping 的输出在一个数组中。但是如果它是一个错误,例如'ping: unknown host lksjdflksjdf.com'它不会返回到$output数组中。

Why is this happening and is there a better method to do this?

为什么会发生这种情况,是否有更好的方法来做到这一点?

回答by Hariprasad

You should redirect stderr to stdout.

您应该将 stderr 重定向到 stdout。

To do that, change your exec() call like this:

为此,请像这样更改您的 exec() 调用:

exec("ping -c 1 $domain_bad 2>&1", $output, $return_var);

More info about 2>&1meaning here.

更多关于此处2>&1含义的信息

回答by Ph?m Tu?n Anh

If the answer above could not solve your problem, maybe exec()is disabled. You can try to check php.inifile at disable_functionsline.

如果上述答案无法解决您的问题,则可能exec()已禁用。您可以尝试在线检查php.ini文件disable_functions