>백엔드 개발 >PHP 튜토리얼 >PHP의 `exec()`에서 표준 오류 출력을 어떻게 캡처할 수 있습니까?

PHP의 `exec()`에서 표준 오류 출력을 어떻게 캡처할 수 있습니까?

Linda Hamilton
Linda Hamilton원래의
2024-11-29 07:39:12551검색

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

PHP에서 Exec() 후 표준 오류 스트림 검색

문제:

You' PHP의 exec() 함수를 사용하여 명령을 다시 실행하고 표준 오류에 기록된 잠재적인 오류 메시지를 캡처하려고 합니다. stream.

해결책:

PHP는 proc_open을 사용하여 표준 출력 및 오류 스트림을 모두 제어하고 캡처하기 위한 보다 포괄적인 접근 방식을 제공합니다.

사용 방법:

  1. 초기화 표준 스트림의 동작을 정의하는 입력/출력(I/O) 설명자 사양:
$descriptorspec = [
    0 => ["pipe", "r"],  // stdin
    1 => ["pipe", "w"],  // stdout
    2 => ["pipe", "w"],  // stderr
];
  1. proc_open을 사용하여 명령을 실행하고 설명자 사양 제공:
$process = proc_open($command, $descriptorspec, $pipes, dirname(__FILE__), null);
  1. 다음을 사용하여 표준 오류 파이프에서 읽습니다. stream_get_contents:
$stderr = stream_get_contents($pipes[2]);

예:

다음 스크립트 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;

PHP 스크립트에서, test.sh를 실행하고 stdout을 캡처할 수 있습니다. 표준 오류:

$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";

출력:

stdout: this is on stdout
this is on stdout too

stderr: this is on stderr
this is on stderr too

위 내용은 PHP의 `exec()`에서 표준 오류 출력을 어떻게 캡처할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.