7

I'm trying to execute a simple Bash Script from PHP script. I collect data from a HTML5 front end page, pass through ajax to the PHP script, take the variables and then, pass these to the .sh script, but I've got messages like:

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

I tried to change the permissions chmod 777 test_bash.sh, tried to modify the sudoers.d file, tried this: shell_exec("echo password_for_the_user | sudo -S command_to_execute"); ... but the Bash script can't write the test.txt file.

Here is my basic code, first the 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
fedorqui 'SO stop harming'
  • 228,878
  • 81
  • 465
  • 523
Sergi
  • 407
  • 5
  • 17

2 Answers2

2

I believe you have to change the permissions on the txt file also in order for apache ( the user that is actually executing the script ) to be able to write to it.

Be careful though when using shell_exec() and changing permissions it is quite easy to pass unwanted variables...

orestiss
  • 1,833
  • 2
  • 14
  • 23
1

When you are saying

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

You are echoing var1, var2 and var3 into the file test.txt that lies in the same directory as the script that is running it.

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

The problem you are facing consists in this error:

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

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

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

Or, probably better, write into another directory. For example /tmp.

Finally, note that it is recommendable to quote your vars. So better say:

echo "$var1 $var2 $var3" > test.txt
#    ^                 ^
Community
  • 1
  • 1
fedorqui 'SO stop harming'
  • 228,878
  • 81
  • 465
  • 523