Home > Backend Development > PHP Tutorial > How to Capture Standard Error (StdErr) from `exec()` in PHP?

How to Capture Standard Error (StdErr) from `exec()` in PHP?

Barbara Streisand
Release: 2024-12-13 02:54:09
Original
327 people have browsed it

How to Capture Standard Error (StdErr) from `exec()` in PHP?

PHP Error Handling in Exec() with StdErr

In PHP, the exec() function executes a command and returns the result, including the URL if the execution is successful. However, you may also want to access error messages through the Standard Error (StdErr) stream. Here's how to do it:

One method to handle StdErr is through the proc_open function, which provides more control over the command execution. Consider the following example:

// Initialize I/O descriptors
$descriptorspec = [
   0 => ["pipe", "r"], // stdin
   1 => ["pipe", "w"], // stdout
   2 => ["pipe", "w"]  // stderr
];

// Execute the command using the descriptors
$process = proc_open('./test.sh', $descriptorspec, $pipes, dirname(__FILE__), null);

// Read from stdout and stderr pipes
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

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

// Output the content of stdout and stderr
echo "stdout :\n";
var_dump($stdout);

echo "stderr :\n";
var_dump($stderr);
Copy after login

In this example, ./test.sh is executed using the specified descriptors, and the output from both stdout and stderr is captured. When executed, the script will display both stdout and stderr contents separately.

By using proc_open, you can effectively handle StdErr and access any error messages generated during command execution in your PHP scripts.

The above is the detailed content of How to Capture Standard Error (StdErr) from `exec()` in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template