Search code examples
phpajaxhtmlbashsudo

Cannot execute Bash script from PHP


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

Solution

  • 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...