Home >Backend Development >PHP Tutorial >How Can I Capture Both stdout and stderr from an Exec() Command in PHP?

How Can I Capture Both stdout and stderr from an Exec() Command in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-30 03:28:16300browse

How Can I Capture Both stdout and stderr from an Exec() Command in PHP?

PHP StdErr after Exec()

In PHP, the exec() function executes a command and returns the output from the command's stdout. However, if the command writes to stderr, this output is not captured by exec().

To capture both stdout and stderr from a command, you can use the proc_open() function. proc_open() provides a greater level of control over the command execution process, including the ability to pipe the command's stdin, stdout, and stderr streams.

Example:

Let's consider the following shell script, test.sh, which writes to both stderr and stdout:

#!/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;

To execute this script in PHP and capture both stdout and stderr, you can use the following code:

$descriptorspec = [
    0 => ['pipe', 'r'],  // stdin
    1 => ['pipe', 'w'],  // stdout
    2 => ['pipe', 'w'],  // stderr
];

$process = proc_open('./test.sh', $descriptorspec, $pipes, dirname(__FILE__), null);

$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);

echo "stdout : \n";
var_dump($stdout);

echo "stderr :\n";
var_dump($stderr);

Output:

When you execute the above PHP script, you will get the following output:

stdout :
string(40) "this is on stdout
this is on stdout too"
stderr :
string(40) "this is on stderr
this is on stderr too"

The output shows the stdout and stderr streams from the test.sh script.

The above is the detailed content of How Can I Capture Both stdout and stderr from an Exec() Command in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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