Run Bash Command from PHP

PhpBashExec

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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);

Solution 2 - Php

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

Solution 3 - Php

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionr0skarView Question on Stackoverflow
Solution 1 - PhpRobert KView Answer on Stackoverflow
Solution 2 - PhpHrishikeshView Answer on Stackoverflow
Solution 3 - PhpCommanderSpockView Answer on Stackoverflow