I have a script in /var/www/myscript.sh which creates folders and run an svn update command for my projects. i need to execute this script by calling it in a PHP file in the browser(Localhost/test.php), I tried the shell_exec() and exec() but did not work. I ran my shell script in terminal with su www-data && ./myscript.sh and it worked. What else am i missing?

    $output = shell_exec("./myscript.sh");

i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works but this is very insecure is there another way to do this

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

    disable_functions = exec

And remove the exec, shell_exec entries if there are there. Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.

I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.

I would recommend moving the shell script to outside of the webroot

  $tempFolder = '/tmp';
  $webRootFolder = '/var/www';
  $scriptName = 'myscript.sh';
  $moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
  $output = shell_exec($moveCommand);

In regards to the:

i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works

You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.

Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.


    sudo su apache (or www-data)
    cd /var/www
    sh ./myscript

Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file

... voila