PHP HTML CSS Tutorials

Tutorials, Resources and Snippets

How to Write a PHP Script to Run Shell Commands from Browser

7 comments

It happens pretty often for me to have to run shell commands in a hosting environment. I do it all the time via a simple php script. I tested it on godaddy and dreamhost and on other hostings environments and it works fine.

Before starting the tutorial you should note that if this script is not handled carefully it can have undesired results. A wrong rm command can delete all the files you have on your hosting, so run the commands with care.

Running Shell Commands from PHP

In the first part of this tutorial we are going to see how we can run a shell command from php and how to retrieve the command ouput. The php function which is responsible to run a shell command is proc_open.

The proc_open function accepts a couple of parameters:

resource proc_open ( string $cmd 
                           , array $descriptorspec
                           , array &$pipes
                         [, string $cwd 
                         [, array $env
                         [, array $other_options ]]] )

We are going to use the first 3 parameters:

  • cmd – the command to execute. The command string will contain the full command as we would write in the shell command line, including the input parameters.
  • descriptorspec – is an indexed array containing the description of the pipes. The first element should contain the input pipe, the second one should contain the output pipe and the third one the stderr(the pipe where the command will return the error it encounter). Each one can be one of the types “pipe” of “file”
  • pipes – is another indexed array that contains the reference to the pipes that are created during process. For example if in the descriptorsspec is specified a pipe for the input, the pipe array will contain the input pipe, which can be used to write to the input stream. The same can happen with the output stream: a pipe can be used to take the output of the command.

    If a pipe is not used, a file can be used instead. Usually temporary files are used. In our example we are going to use a pipe for the input and tmp files for the output and for the stderr. Because we don’t need to pass any input file to the command we are going to close the input pipe immediately, without writing anything in it.

The proc_open function will be run slightly different on windows and linux environments. Windows processes don’t return a stderr, so it can not be used to test the success of a command on and windows environment.

Here is the function we are going to use to run a command:

function cmd_exec($cmd, &$stdout, &$stderr)
{
   $outfile = tempnam(".", "cmd");
   $errfile = tempnam(".", "cmd");
   $descriptorspec = array(
       0 => array("pipe", "r"),
       1 => array("file", $outfile, "w"),
       2 => array("file", $errfile, "w")
   );
   $proc = proc_open($cmd, $descriptorspec, $pipes);
  
   if (!is_resource($proc)) return 255;

   fclose($pipes[0]);    //Don't really want to give any input

   $exit = proc_close($proc);
   $stdout = file($outfile);
   $stderr = file($errfile);

   unlink($outfile);
   unlink($errfile);
   return $exit;
}

Adding a Form

Now that we wrote the function to run a shell command from php, we need to write a html form from where to trigger the execution of the shell commands. First we define an html form:

Command:

And finally we add the code to run the command entered in the form:

if (isset($_POST['command']))
{
	echo 'Command: ' . $_POST['command'] . '
'; $exit = cmd_exec($_POST['command'],$stdout, $stderr); //print the output foreach ($stdout as $line) { echo "$line
"; } //in case there an error is returned foreach ($stderr as $line) { echo "$line
"; } }

Now all you have to do is to put all the snippets described above in a php file. Of you can download it from here. You have to use with caution and keep in mind that it is not protected by password. In the next tutorial we are going to ad a login form to the script.

Did you enjoy this tutorial? Be sure to subscribe to the our RSS feed not to miss our new tutorials!
... or make it popular on

Written by admin

July 28th, 2009 at 10:44 am

Posted in howto

Tagged with , ,

7 Responses to 'How to Write a PHP Script to Run Shell Commands from Browser'

Subscribe to comments with RSS or TrackBack to 'How to Write a PHP Script to Run Shell Commands from Browser'.

  1. Here is another (related) tip.
    There are times when I am not interested in standard or error out. But I want to know if the unix command was successfully run or not.

    passthru(“gunzip “.$dir_path.$synarray[$y].”.sql.gz > /dev/null 2>&1″,$returnvalue);

    if ($returnvalue != 0)
    {
    $brkflag=1;

    break;

    }

    In the above example if the value of “brkflag” is set to 1 then there was some problem.

    Shantanu Oak

    4 Mar 10 at 3:47 am

  2. for example when i try

    cat /var/log/apache2/error.log

    i get

    cat: /var/log/apache2/error.log: Permission denied

    how can i pass it?

    loth

    10 Mar 10 at 7:08 am

  3. You have to chmod your file to 755 or give the permission as required to run the script.

    Ilyas

    15 Mar 10 at 11:40 am

  4. Dude! AWESOME Script. Exactly what I needed to download the code of a site for an emergency fix tonight. You probably just gave me back 3 hours of sleep. Thanks!

    Joey

    30 Sep 11 at 6:28 pm

  5. Why wouldn’t you just use back ticks?
    i.e.

    $myCMD = `curl –data “birthday=September” http://www.SomeDomain.com/SomePage.php`;

    OR…. the system with escapeshellcmd..

    system(‘curl http://www.SomeDomain.com/?birthday=September‘);

    Grant

    21 Feb 12 at 10:34 pm

  6. Hi, this is a great piece of script. It works nicely on shell scripst or commands, but I wonder how to tweak it to run a GUI program.
    When I try to run a gui program, it freezes (i think it waits for program which does not even start). Do you have any idea?
    Thanks a lot!

    WBR

    3 May 12 at 1:19 pm

  7. Can you tell me how to change directory using this script. like when i use the command cd.. to go one directory down and then again when i use the command cd. I shows that the directory is still same and is not getting changed

    Andy

    23 May 12 at 2:26 am

Leave a Reply