简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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