如何执行shell命令并从PHP中回显多行


How to execute shell command and echo multiple lines from PHP?

Re,

我使用shell命令cat将多行转储到一个文件中,如下所示:

cat > file <<CHAR
one
two
three
CHAR

我的问题是:我需要在PHP中使用shell_exec执行相同的cat命令。如何转储数组的内容并使用CHAR终止命令?我知道这听起来很奇怪,但我需要使用sudo创建一个文件,我不想把所有东西都转储到一个临时文件中,然后用sudo cp将其转储到指定的位置。

谢谢。

这样做:

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

当然,只有当底层shell支持here-doc语法时,这才会起作用。

使用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);