Executing a shell script from a PHP script

nmadhok picture nmadhok · Jun 17, 2013 · Viewed 100.7k times · Source

I want to execute a Bash script present on the system from a PHP script. I have two scripts present on the system. One of them is a PHP script called client.php present at /var/www/html and the other is a Bash script called testscript present at /home/testuser.

My client.php script looks like

<?php
  $message=shell_exec("/home/testuser/testscript 2>&1");
  print_r($message);
?>  

My testscript looks like

#!/bin/bash
echo "Testscript run succesful"

When i do the following on terminal

php client.php

I get the following output on terminal

Testscript run successful

But when i open the page at

http://serverdomain/client.php

I get the following output

sh: /home/testuser/testscript: Permission denied 

I get this error even after I did chmod +x testscript.
How do I get it to work from the browser? Please help.

Answer

Panama Jack picture Panama Jack · Jun 17, 2013

I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP.

e.g. /var/www/scripts/testscript

Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache, change the bash script to the same user/group using chown. You can find out what your client.php and web files are owned by doing ls -al.

Then run

<?php
      $message=shell_exec("/var/www/scripts/testscript 2>&1");
      print_r($message);
    ?>  

EDIT:

If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do.

Execute root commands via PHP