简体   繁体   中英

Executing unix shell commands using PHP

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 this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

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 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.

Eg:

exec('ls -la', $outputArray);
print_r($outputArray);

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.

Try $output = shell_exec('ls -lart');

doc shell_exec

As long as it is one line you can just echo the return value of exec .

Like so:

echo exec('ls');

But it only displays the first line.

exec(escapeshellarg($userSuppliedInput), $output);

echo $output;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM