Home > Backend Development > PHP Tutorial > PHP executes the shell script and gets the standard output and error output

PHP executes the shell script and gets the standard output and error output

WBOY
Release: 2016-09-08 08:29:36
Original
1579 people have browsed it

1. Question

You need to execute a shell script in the php code, and hope to get its standard output (stdout) and error output (stderr) respectively. Using shell's redirect to put the standard output and error output into a file and then using php to read the file is feasible, but the content of the output file is no longer needed after it is transferred back to php. Is there a way to redirect the shell's output to variable?

To execute the function of the script, it cannot be completed with PHP itself (execute the script in R language), and both regular output and error output need to be fed back.

2.Already tried

Redirection

in shell can put the standard output and error output into files respectively, but generate temporary files.

<code class="bash">my_cmd 1>out.txt 2>err.txt</code>
Copy after login
php then reads the contents of the

out.txt and err.txt files and returns them.

Disadvantages of this: intermediate files are generated. If the shell command

my_cmd takes a long time to execute (maybe several minutes), then if the same user initiates multiple http requests in a short period of time to cause php to execute my_cmd, out.txt and err will be required each time. The names of txt are all different to avoid writing conflicts. This produces a lot of unnecessary intermediate files. Even if they are deleted in time, there will still be I/O overhead, which I hope can be avoided.

php’s

exec() function:

<code>string exec ( string $command [, array &$output [, int &$return_var ]] )</code>
Copy after login
The parameters inside $output

seem to only get the content of "screen output when running the script", which is stdout or a mixture of stdout and stderr and cannot be obtained separately.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template