Cannot execute bash script from PHP

I am trying to execute a simple Bash Script from a PHP script. I collect data from the first page of HTML5 , go through ajax to a PHP script, take the variables, and then pass them to the .sh script, but I have messages like:

 ./test_bash.sh: line 13: ./test.txt: Permission denied 

I tried changing the permissions of chmod 777 test_bash.sh , tried to change the sudoers.d file, tried this: shell_exec("echo password_for_the_user | sudo -S command_to_execute"); ... but Bash Script could not write the test.txt file.

Here is my base code, first PHP code :

 <?php $var1 = json_decode($_POST['var1']); //from front-end html5 $var2 = json_decode($_POST['var2']); $var3 = json_decode($_POST['var3']); $response = shell_exec("./test_bash.sh $var1 $var2 $var3 2>&1"); echo "$response"; ?> 

Secondly, the Bash code:

 #!/bin/bash var1=$1; var2=$2; var3=$3; echo "$var1"; echo "$var2"; echo "$var3"; echo $var1 $var2 $var3 > ./test.txt 
+7
bash html5 ajax php sudo
source share
2 answers

I believe that you need to change permissions on the txt file also so that apache (the user who actually runs the script) to write to it.

Be careful, but when using shell_exec() and changing permissions, it's pretty easy to pass unwanted variables ...

+2
source share

When you speak

 echo $var1 $var2 $var3 > ./test.txt 

You echo ing var1, var2 and var3 into the test.txt file, which is located in the same directory as the script that runs it.

So, if you are in /var/www , the execution of echo $var1 $var2 $var3 > ./test.txt will be the same as for echo $var1 $var2 $var3 > /var/www/test.txt .

The problem you are facing is this error:

./test_bash.sh: line 13: ./ test.txt: Permission denied

This tells you that you are not allowed to write to the /var/www/test.txt file. To do this, change the write permissions to this file so that "others" can be written to it (that is, the www or apache user):

 chmod o+w /var/www/test.txt 

Or perhaps better, write to another directory. For example /tmp .

Finally, note that it is recommended that you quote your var . So it’s better to say:

 echo "$var1 $var2 $var3" > test.txt # ^ ^ 
+1
source share

All Articles