Run Bash Command from PHP

I have a bash script, that I run like this via the command line:

./script.sh var1 var2

I am trying to execute the above command, after I call a certain php file.

What I have right now is:

$output = shell_exec("./script.sh var1 var2");
echo "<pre>$output</pre>";

But it doesn´t work. I tried it using exec and system too, but the script never got executed.

However when I try to run shell_exec("ls"); it does work and $output is a list of all files.

I am not sure whether this is because of a limitation of the VPS I am using or if the problem is somewhere else?


You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.

$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);

Your shell_exec is executed by www-data user, from its directory. You can try

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/bin Later on you can

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh