Home >Backend Development >PHP Tutorial >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);
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!