"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-12-13
Browse:555

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3