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.

4

2 回答 2

1

像这样做:

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

当然,这只有在底层 shell 支持 here-doc 语法时才有效。

于 2013-08-09T01:05:36.503 回答
1

使用popen()代替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);
于 2013-08-09T01:15:36.060 回答