Search code examples
phpvariablesexecis-empty

Exec or Shell_exec: variables don't pass from php to the script


I tried many tests, but my 2 variables just don't pass, while a variable set within the script is indeed passed back correctly to PHP.

HTML/PHP code extract:

<?php
$subject = $_POST['subject'];
$body = $_POST['body'];
$output = null;
exec('../scripts/my-script.sh $subject $body', $output);
?>
<p><?php echo "<pre>" . var_export($output, TRUE) . "</pre>";?></p>

my-script.sh:

subject=$1
body=$2
cd ~/scripts/
path=`pwd`
#
echo "--"$path >> ./log.txt
echo "--"$subject >> ./log.txt
echo "--"$body >> ./log.txt
#
echo "=="$path
echo "=="$subject
echo "=="$body
only $path gets written in log.txt, and passed back to php.
The 2 other variables subject and body are empty;

html output:

array (
0 => '==/home/account/scripts',
1 => '==',
2 => '==',
)

log.txt content:

--/home/account/scripts
--
--

I tried to insert double quotes and format in different ways the variables within the exec function call, but the variables subject and body always appear empty both in log.txt and back in HTML/PHP.

exec('../scripts/my-script.sh "$subject" "$body"', $output);
exec('../scripts/my-script.sh'.' '.$subject.' '.$body, $output);

Any idea very welcome !


Solution

  • Doubles quotes should be at the beginning of the string.

    'some string "$var" somestring' // won't interpolate
    "some string '$var' somestring" // will interpolate
    

    or you can concatenate them to the string

    exec('../ems-scripts/mass-email-send.sh ' . $subject . ' ' . $body, $output)
    

    You can read this discussion Should I use curly brackets or concatenate variables within strings? your problem is more about variable concatenation and interpolation, than really about exec() and shell_exec()