简体   繁体   English

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

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

Re, 回覆,

I use a shell command cat to dump multiple lines into a file like so: 我使用shell命令cat将多行转储到文件中,如下所示:

cat > file <<CHAR
one
two
three
CHAR

Here's my problem: I need to execute the same cat command using shell_exec in PHP. 这是我的问题:我需要在PHP中使用shell_exec执行相同的cat命令。 How would I dump the contents of an array and terminate the command with CHAR ? 如何转储数组的内容并使用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. 我知道这听起来很奇怪,但我需要用创建一个文件sudo ,我不想一切倾倒到一个临时文件,然后sudo cp到预期的位置。

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. 当然,这仅在底层shell支持here-doc语法时才有效。

Use popen() instead of shell_exec() : 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM