Home > Backend Development > PHP Tutorial > How Can I Capture Standard Error Output from `exec()` in PHP?

How Can I Capture Standard Error Output from `exec()` in PHP?

Linda Hamilton
Release: 2024-11-29 07:39:12
Original
508 people have browsed it

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:

  1. Initialize input/output (I/O) descriptor specifications, which define the behavior of standard streams:
$descriptorspec = [
    0 => ["pipe", "r"],  // stdin
    1 => ["pipe", "w"],  // stdout
    2 => ["pipe", "w"],  // stderr
];
Copy after login
  1. Execute the command using proc_open and provide the descriptor specifications:
$process = proc_open($command, $descriptorspec, $pipes, dirname(__FILE__), null);
Copy after login
  1. Read from the standard error pipe using stream_get_contents:
$stderr = stream_get_contents($pipes[2]);
Copy after login

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;
Copy after login

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";
Copy after login

Output:

stdout: this is on stdout
this is on stdout too

stderr: this is on stderr
this is on stderr too
Copy after login

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!

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