本文翻译自:PHP shell_exec() vs exec()
I'm struggling to understand the difference between
I've always used
Is
#1楼
参考:https://stackoom.com/question/TlR6/PHP-shell-exec-与exec
#2楼
Here are the differences. 这是区别。 Note the newlines at the end. 注意最后的换行符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | > shell_exec('date') string(29) "Wed Mar 6 14:18:08 PST 2013\n" > exec('date') string(28) "Wed Mar 6 14:18:12 PST 2013" > shell_exec('whoami') string(9) "mark\n" > exec('whoami') string(8) "mark" > shell_exec('ifconfig') string(1244) "eth0 Link encap:Ethernet HWaddr 10:bf:44:44:22:33 \n inet addr:192.168.0.90 Bcast:192.168.0.255 Mask:255.255.255.0\n inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1\n RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n collisions:0 txqueuelen:1000 \n RX bytes:13151177627 (13.1 GB) TX bytes:2779457335 (2.7 GB)\n"... > exec('ifconfig') string(0) "" |
Note that use of the backtick operator is identical to
Update: I really should explain that last one. 更新:我真的应该解释最后一个。 Looking at this answer years later even I don't know why that came out blank! 多年以后,看着这个答案,我什至不知道为什么会显得空白! Daniel explains it above -- it's because
#3楼
A couple of distinctions that weren't touched on here: 这里没有涉及的几个区别:
- With exec(), you can pass an optional param variable which will receive an array of output lines. 使用exec(),您可以传递一个可选的param变量,该变量将接收输出行数组。 In some cases this might save time, especially if the output of the commands is already tabular. 在某些情况下,这可能节省时间,尤其是在命令输出已经以表格形式显示的情况下。
Compare: 相比:
1 2 3 4 5 6 7 | exec('ls', $out); var_dump($out); // Look an array $out = shell_exec('ls'); var_dump($out); // Look -- a string with newlines in it |
Conversely, if the output of the command is xml or json, then having each line as part of an array is not what you want, as you'll need to post-process the input into some other form, so in that case use shell_exec. 相反,如果命令的输出是xml或json,则不需要将每一行作为数组的一部分,因为您需要将输入后处理为其他形式,因此在这种情况下,请使用shell_exec 。
It's also worth pointing out that shell_exec is an alias for the backtic operator, for those used to *nix. 还值得指出的是,shell_exec是backtic运算符的别名,对于* nix而言是这样的。
1 2 | $out = `ls`; var_dump($out); |
exec also supports an additional parameter that will provide the return code from the executed command: exec还支持一个附加参数,该参数将提供已执行命令的返回代码:
1 2 3 4 5 6 | exec('ls', $out, $status); if (0 === $status) { var_dump($out); } else { echo "Command failed with status: $status"; } |
As noted in the shell_exec manual page, when you actually require a return code from the command being executed, you have no choice but to use exec. 如shell_exec手册页所述,当您实际上需要从正在执行的命令中返回代码时,您别无选择,只能使用exec。
#4楼
See 看到
- http://php.net/manual/en/function.shell-exec.php http://php.net/manual/zh/function.shell-exec.php
- http://php.net/manual/en/function.exec.php http://php.net/manual/zh/function.exec.php
#5楼
The difference is that with