Home > Article > Backend Development > PHP executes the shell script and gets the standard output and error output
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
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>php then reads the contents of the
out.txt and
err.txt files and returns them.
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.
exec() function:
<code>string exec ( string $command [, array &$output [, int &$return_var ]] )</code>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.