PHP shell_exec() vs exec()
我正在努力了解
我一直使用
看到
- http://php.net/manual/zh/function.shell-exec.php
- http://php.net/manual/zh/function.exec.php
这是区别。注意最后的换行符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | > shell_exec('date') string(29)"Wed Mar 6 14:18:08 PST 2013 " > exec('date') string(28)"Wed Mar 6 14:18:12 PST 2013" > shell_exec('whoami') string(9)"mark " > exec('whoami') string(8)"mark" > shell_exec('ifconfig') string(1244)"eth0 Link encap:Ethernet HWaddr 10:bf:44:44:22:33 inet addr:192.168.0.90 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0 TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:13151177627 (13.1 GB) TX bytes:2779457335 (2.7 GB) "... > exec('ifconfig') string(0)"" |
请注意,反引号运算符的使用与
更新:我真的应该解释最后一个。多年以后,看着这个答案,我什至不知道为什么会显得空白! Daniel在上面进行了解释-这是因为
区别在于,使用
这里没有涉及的几个区别:
- 使用exec(),您可以传递一个可选的param变量,该变量将接收输出行数组。在某些情况下,这可能节省时间,尤其是在命令输出已经以表格形式显示的情况下。
相比:
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 |
相反,如果命令的输出是xml或json,则不需要将每一行作为数组的一部分,因为您需要将输入后处理为其他形式,因此在这种情况下,请使用shell_exec 。
还值得指出的是,shell_exec是backtic运算符的别名,对于* nix而言是这样的。
1 2 |
exec还支持一个附加参数,该参数将提供已执行命令的返回代码:
1 2 3 4 5 6 |
如shell_exec手册页所述,当您实际上需要从正在执行的命令中返回代码时,您别无选择,只能使用exec。