Shell heredoc inside php heredoc

I have something similar to a php script:

<?php
...
function log() {
    // saving the log into a file.
    exec(<<<BASH
cat >> $logFile <<EOF
$log
EOF
BASH
    );
}
...

As you can see, there are two heredocs (BASH is php and EOF is the shell), as you might think correctly, but when I read the created log, there is something like this in the log:

...
my logged string of an important event
EOF
my logged string of another important event
EOF
...

And I check the apache log and has the following entries:

sh: line 1: warning: here-document at line 0 delimited by end-of-file (wanted `EOF')

What am I doing wrong?

Please, I know that there are many other implementations, such as using php functions or using quotes instead of heredocs. But I'm curious why in this particular case this does not work.

EDIT. I refined the code, so it’s more clear that I'm talking about php executing shell commands.

+4
source share
1 answer

PHP

, test.php :

<?php
function mylog() {
  $logFile = 'test.log';
  $log = 'test';

  exec(<<<BASH
cat >> $logFile <<EOF
$log
EOF
BASH
     );
}

mylog();

php test.php (!):

rm -f test.log
php test.php
cat test.log

:

test

Bash:

<?php
function mylog() {
  $logFile = 'test.log';
  $log = 'test';

  exec(<<<BASH
  cat >> $logFile <<EOF
  $log
  EOF
BASH
     );
}

mylog();

php test.php , :

rm -f test.log
php test.php
cat test.log

:

sh: line 2: warning: here-document at line 0 delimited by end-of-file (wanted `EOF')
  test
  EOF

-, Bash, Bash. Bash. , EOF .

, , OP Bash

exec , Bash. eval.

eval, :

eval "$(
cat <<'EOF'

cat >> test.log <<EOF2
log contents
EOF2

EOF
)"

, Bash "$( )". -doc cat <<'EOF' EOF, , ( ). log contents -doc, <<EOF2 EOF2.

Bash, , :

cmd="$(
cat <<'EOF'

cat >> test.log <<EOF2
log contents
EOF2

EOF
)"

rm test.log
eval "$cmd"; eval "$cmd"; eval "$cmd"
cat test.log

:

log contents
log contents
log contents

.

+2

All Articles