A text box will be used to capture the command. I\'ve been told that I have to use the exec()
function to execute UNIX shell commands.
Something like th
Try $output = shell_exec('ls -lart');
doc shell_exec
exec(escapeshellarg($userSuppliedInput), $output);
echo $output;
exec
?
system
?
shell_exec
?
passthru
?
Backticks?
Pfah!
Real developers use proc_open! It has the major and distinct advantage of giving you three PHP streams to feed data into the process, and read both stdout
and stderr
. This is something that the other process execution functions simply don't do well.
It comes at the small cost of some boilerplate code, so it's a bit more verbose. I consider the trade-off to be excellent.
Oh, and running arbitrary commands from your users is perhaps one of the greatest security risks that you could ever conceive of, but I kind of assume you know this by now.
You can use the backticks for this purpose. Like:
$output = `command-executable -switches`
In addition, some applications echo their output to the STD_ERR stream so you might not see output. On linux, you can redirect the error input to the 'normal' input by appending 2>&1
to the command string.
Use $output = system($command);
See http://php.net/system and don't forget to read the warnings about security. If you let a user pass any data to system()
(or exec()
etc.) it's almost as if they had a shell on your server. The same applies if you don't sanitize arguments passed to programs executed through these functions properly.
You could start looking at the php manual:
System program execution
But like sdleihssirhc mentioned, watchout this IS very dangerous and you should NOT allow everything to be executed!
If you still want to do it, to get the output of the shell, just use
exec
The output of the shell will be passed in the second parameter.
E.g.:
exec('ls -la', $outputArray);
print_r($outputArray);