Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing unix shell commands using PHP

Tags:

shell

php

unix

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.

like image 733
user478636 Avatar asked Apr 12 '11 07:04

user478636


People also ask

Can PHP run shell command?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix.

How do I run a PHP script in Linux?

You can execute linux commands within a php script - all you have to do is put the command line in brackits (`). And also concentrate on exec() , this and shell_exec() .. Save this answer.

What is PHP shell script?

PHP Shell or Shell PHP is a program or script written in PHP (Php Hypertext Preprocessor) which provides Linux Terminal (Shell is a much broader concept) in Browser. PHP Shell lets you to execute most of the shell commands in browser, but not all due to its limitations.


2 Answers

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.

like image 92
Charles Avatar answered Sep 19 '22 10:09

Charles


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.

like image 25
ThiefMaster Avatar answered Sep 19 '22 10:09

ThiefMaster