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);
Answer from Robert K on Stack Overflow
🌐
PHP
php.net › manual › en › function.shell-exec.php
PHP: shell_exec - Manual
There are cases where you need the output to be logged somewhere else though. Redirecting the output to a file like this didn't work for me: <?php # this doesn't work! shell_exec("my_script.sh 2>&1 >> /tmp/mylog &"); ?> Using the above command still hangs web browser request.
Discussions

Bash script to run php script - Stack Overflow
As far as I'm aware I need to create the bash script to handle the php script which will then allow me to use the Cron tool/timer. ... Any advice? Thanks. ... If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this: ... Put that at the top of your script, make it executable ... More on stackoverflow.com
🌐 stackoverflow.com
How to run a bash script from PHP - Unix & Linux Stack Exchange
Also, why are you sending json ... not json, since you are testing for a string in the PHP/bash. Try as a start to read the documentation on these, otherwise you will never learn. ... Is the script executable?... More on unix.stackexchange.com
🌐 unix.stackexchange.com
Any way to SAFELY execute shell scripts from PHP?
Executing other applications (whether it's a shell script or something else) from a PHP application is not unsafe per se. The security depends heavily on how safe the application is and how much a user can control of the input. You must ensure a user never can control what exact command line is executed (and ensure that every parameter is properly escaped). If not absolutely necessary the user should also not control parameters of the application (and if only a specified subset of them). As long as you just call a static script without any dynamic input which is somehow user controllable, you should be relatively safe if the application and the action performed is safe. Maybe you should think about restricting or sandboxing the called applications (using techniques like selinux, user permissions, or containers), so it can only do its desired job and can do as little harm as possible. More on reddit.com
🌐 r/PHPhelp
10
9
February 26, 2024
apache - Executing a shell script from a PHP script - Stack Overflow
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 oth... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
5

The problem here is that you are quoting the entiore command you are trying to run as a single variable. As a result, you're not running php with foo.php as an argument but instead are attempting to execute a file called php foo.php. Here's a simpler example to show you what I mean:

$ var1="echo "
$ var2="foo"
$ set -x ## debugging info
var1$var2"
+ 'echo foo'      ### The shell tries to execute both vars as a single command
bash: echo foo: command not found

var1" "$var2"
+ 'echo ' foo     ### The shell tries to execute 'echo ' (echo with a space)
bash: echo foo: command not found  

So, the right way is to remove the space and quote each variable separately:

$ var1="echo"
$ var2="foo"
var1" "$var2"

If you do that though, you'll hit the next error. The . is the source command. That tries to read a shell script and execute it in the current session. You are giving it a php script instead. That won't work, you need to execute it, not source it.

Finally, always avoid using CAPITAL variable names. The shell's reserved variables are capitalized so it's a good idea to always use lower case variable names for your scripts.

Putting all this together (with a few other minor improvements), what you want is something like:

#!/bin/sh

list="/path/to/my/site/dir"
config="/usr/bin/php"

for i in "$list"
do
    "$config" "$i"/test.php
done
2 of 3
5

The problem in your code is the line:

. "${CONFIG}${i}/test.php"  

Remove the .


Here is another example:

$ ls -l

-rwxrwxr-x 1 bg bg 67 Oct 20 09:42 index.php
-rwxrwxr-x 1 bg bg 68 Oct 20 09:43 test.sh

index.php

<?php
    shell_exec('echo Hello > /tmp/hello.txt');
?>

test.sh

#!/bin/bash
/usr/bin/php index.php
🌐
Stack Exchange
unix.stackexchange.com › questions › 708392 › how-to-run-a-bash-script-from-php
How to run a bash script from PHP - Unix & Linux Stack Exchange
<?php $old_path = getcwd(); chdir('/home/scripts/'); $var = escapeshellarg("PC7"); $output = shell_exec("./Script2.sh $var"); chdir($old_path); echo $output; ?> ... #!/bin/bash var=$1 if [ "$var" == "PC7" ]; then echo "Strings are equal" else echo "Strings are not equal" fi · Now I need to use this inside a PHP function to execute whenever I click a button...
🌐
Reddit
reddit.com › r/phphelp › any way to safely execute shell scripts from php?
r/PHPhelp on Reddit: Any way to SAFELY execute shell scripts from PHP?
February 26, 2024 -

I have a website accessible from https://exampleurl.com:1234 (i.e. nonstandard port).

After logging in, this website gives my users a GUI and a few buttons. The buttons interact with PHP scripts on an Unraid VM, which then launch shell scripts. The shell scripts are used for controlling streams via streaming software called "OBS-Studio".

Here's an example:

my.php
<?php
$output = shell_exec("/bin/bash /var/www/html/streamstart.sh");
echo $output; 
?>


streamstart.sh
#!/bin/bash
obs-cmd streaming start

I'm relatively new to PHP, and I'm not sure how this could be exploited. Is there a way to make this more secure?

I have set the password for my users to be extremely secure, but that feels like the only line of defense right now.

Top answer
1 of 5
6
Executing other applications (whether it's a shell script or something else) from a PHP application is not unsafe per se. The security depends heavily on how safe the application is and how much a user can control of the input. You must ensure a user never can control what exact command line is executed (and ensure that every parameter is properly escaped). If not absolutely necessary the user should also not control parameters of the application (and if only a specified subset of them). As long as you just call a static script without any dynamic input which is somehow user controllable, you should be relatively safe if the application and the action performed is safe. Maybe you should think about restricting or sandboxing the called applications (using techniques like selinux, user permissions, or containers), so it can only do its desired job and can do as little harm as possible.
2 of 5
1
Executing a process from PHP is not inherently unsafe. There are some common scenarios that can create safety issues, though. First you have to realize that PHP is basically like a virtual user on the server. When you tell it to run a process, it runs that process with the user account that PHP is running as. So if PHP is running as a user account named "phpuser", and you tell PHP to run /usr/bin/foobar, then it'll be the same as if you logged into the server with the "phpuser" login and then ran foobar. That's not unsafe for you to log in and run that command, but let's pretend for a moment that you can't run foobar - it gives you some security error message. You look closer and see that foobar can only be executed by the "root" superuser account. The appropriate fix might be to see if the permissions on foobar are incorrect and need correction. Or it might actually be that you need to be root. The wrong thing here is to "fix" it by running PHP as root but some people do that. If PHP is ever compromised, then the attacker gets root-level access to the entire system. So the first thing to know is that you should never increase the permissions of the PHP to get around a security restriction. In almost every case, there is a better way, even if it's permitting sudo for just that one command. The second thing is to be aware that whatever information you pass on the command line will be visible to anyone else on the system who is looking at the list of running processes. So if I ran shell_exec("/usr/bin/customservice --password=FOOBAR"); ...then while customservice was running, anyone who listed the processes with ps or top would be able to see that password. So don't put any sensitive information into a parameter. The third thing is to know that environment variables will propagate from PHP to the child process you run. Some people follow the bad (but currently popular) practice of using environment variables for credentials. So make sure you clear any sensitive env variables before launching the process, so that the process doesn't accidentally leak them. Lastly, and most importantly, don't ever take user input and use it within the command line (unless you've heavily sanitized it).
Find elsewhere
🌐
Linux Hint
linuxhint.com › execute_shell_command_php
Execute Shell Command in PHP using exec() – Linux Hint
Create a PHP file with the following script to run the bash script. ‘bash loop.sh‘ is used as the first argument of the exec() function that will execute the loop.sh script file.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › community › general discussion
Running a bash script via PHP - Raspberry Pi Forums
#!/bin/bash SCRIPT="screen -dmS minecraft ~/server1/load.sh" HOSTS="Minecraft_Pi" for HOSTNAME in ${HOSTS} ; do ssh ${HOSTNAME} "$SCRIPT" done My PHP script to run the external launch script (my second pi is running an Nginx server with PHP 7.0):
Top answer
1 of 4
21

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

2 of 4
5

Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

For A Debian box with Apache and sudo:

  1. Configure sudo:

    • As root, run the following to edit a new/dedicated configuration file for sudo:

      visudo -f /etc/sudoers.d/Webserver
      

      (or whatever you want to call your file in /etc/sudoers.d/)

    • Add the following to the file:

      www-data ALL = (root) NOPASSWD: <executable_file_path>
      

      where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

      For example, say we always want to copy the same file in the /root/ directory, we would write the following:

      www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
      
  2. Modify the script(testscript):

    Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

    sudo /bin/cp /root/test1 /root/test2
    

If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

Keep in mind:

When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

🌐
Super User
superuser.com › questions › 1124268 › php-calling-bash-script
linux - PHP calling Bash-script - Super User
September 14, 2016 - <?php $old_path = getcwd(); chdir('/var/www/html/SOKHJALPMEDEL/'); $term1 = $_POST['query1']; $argument1 = $_GET['$term1']; $term2 = $_POST['query2']; $argument2 = $_GET['$term2']; echo $nu_kor_vi1; $outcome = shell_exec("sokare $argument1 $argument2"); chdir($old_path); echo "<pre>$outcome</pre>"; ?> The script is calling a Bash-script "sokare" that is executable systemwide and residning in "/usr/local/bin".
🌐
Linux Tip
linuxscrew.com › home › programming › php › how to execute php from the command line (bash/shell)
How to Execute PHP from the Command Line (Bash/Shell)
October 22, 2021 - PHP commands can be executed directly from the command line with the -r (run) option: ... Above, the phpinfo() function is called. Multiple lines of code can be passed separated by a semicolon, or a heredoc (multiline Bash variable) ...
🌐
Squash
squash.io › utilizing-variables-from-bash-scripts-in-php-on-linux
Utilizing Variables from Bash Scripts in PHP on Linux
This can be useful when you have large or complex data structures that need to be shared between the scripts. For example, you can write the variables to a file in Bash and then read the file in PHP to access the values. Here's an example of how you can share variables between Bash and PHP using temporary files: #!/bin/bash # Define variables name="John" age=25 # Write variables to a temporary file echo "$name" > /tmp/variables.txt echo "$age" >> /tmp/variables.txt # Execute PHP script php myscript.php