0

Re,

I use a shell command cat to dump multiple lines into a file like so:

cat > file <<CHAR
one
two
three
CHAR

Here's my problem: I need to execute the same cat command using shell_exec in PHP. How would I dump the contents of an array and terminate the command with CHAR? I know this sounds odd but I need to create a file using sudo and I don't want to dump everything into a temporary file and then sudo cp it to the intended location.

Thanks.

2 Answers 2

1

Do it like this:

shell_exec('cat > file <<EOF
foo
bar
EOF
');

Of course this will only work if the underlying shell supports the here-doc syntax.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I had to implode my array using PHP_EOL to make it work.
Your join with \n won't work as it will produce a single-line file with line breaks not being recognized. That's why I used PHP_EOL
I've tested this code. you need double quotes if you need escape sequences: "\n".
1

Use popen() instead of shell_exec():

$filename = 'file';
$text = 'CHAR
one
two
three
';

$cmdline = 'cat > ' . escapeshellarg($filename);
$fp = popen('sudo /bin/sh -c ' . escapeshellarg($cmdline), 'w');
fwrite($fp, $text);
pclose($fp);

1 Comment

popen is an interesting alternative. thanks, I will read up on it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.