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.
题
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.
解决方案
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.
其他提示
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);