PHP shell_exec() vs exec() PHP shell_exec() vs exec() shell shell

PHP shell_exec() vs exec()


shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.

See


Here are the differences. Note the newlines at the end.

> 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 shell_exec().

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 exec only returns the last line, and ifconfig's last line happens to be blank.


shell_exec - Execute command via shell and return the complete output as a string

exec - Execute an external program.

The difference is that with shell_exec you get output as a return value.