Home >Backend Development >PHP Tutorial >How Can I Capture Standard Error Output from `exec()` in PHP?
Retrieve Standard Error Stream after Exec() in PHP
Problem:
You're executing a command using PHP's exec() function and want to capture potential error messages written to the standard error stream.
Solution:
PHP provides a more comprehensive approach for controlling and capturing both standard output and error streams using proc_open.
How to Use:
$descriptorspec = [ 0 => ["pipe", "r"], // stdin 1 => ["pipe", "w"], // stdout 2 => ["pipe", "w"], // stderr ];
$process = proc_open($command, $descriptorspec, $pipes, dirname(__FILE__), null);
$stderr = stream_get_contents($pipes[2]);
Example:
Consider the following script test.sh:
#!/bin/bash echo 'this is on stdout'; echo 'this is on stdout too'; echo 'this is on stderr' >&2; echo 'this is on stderr too' >&2;
In a PHP script, we can run test.sh and capture stdout and stderr:
$descriptorspec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]]; $process = proc_open('./test.sh', $descriptorspec, $pipes); $stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]); echo "stdout: $stdout"; echo "stderr: $stderr";
Output:
stdout: this is on stdout this is on stdout too stderr: this is on stderr this is on stderr too
The above is the detailed content of How Can I Capture Standard Error Output from `exec()` in PHP?. For more information, please follow other related articles on the PHP Chinese website!