2010-02-23 2 views
43

PHP에서 exec()를 사용하여 명령을 실행 중이며 URL이 성공하면 반환됩니다.Exec() 이후의 PHP StdErr

$url = exec('report'); 

그러나 뭔가 잘못되면 stderr을 확인하고 싶습니다. 스트림을 어떻게 읽습니까? php : // stderr를 사용하고 싶지만 어떻게 사용하는지 모르겠습니다.

+0

Symfony/Process 구성 요소를 사용하는 것이 좋습니다. –

답변

65

당신은 아마 실행되고있는 명령 제어의 훌륭한 수준 제공 proc_open 사용하는 것, 해결책을 명령을 실행하고 stderrstdout 모두가 아니라 "병합"얻고 싶은 경우에 - 방법을 포함하여 파이프에 stdin/stdout/stderr.


그리고 여기가 예입니다 temp.php에 코드를의 일부 PHP를하자, 이제

#!/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; 


: 이제 우리는 모두 stderrstdout에 기록하는, test.sh,이 쉘 스크립트를 살펴 보자

$descriptorspec = array(
    0 => array("pipe", "r"), // stdin 
    1 => array("pipe", "w"), // stdout 
    2 => array("pipe", "w"), // stderr 
); 


: - 첫째, 우리는 I/O 기술자를 초기화그리고, 다음, 현재 디렉토리에, 그 기술자를 사용하고, I/O가에서/$pipes에해야 말하 test.sh 명령을 실행 : 우리는 이제 두 개의 출력 파이프에서 읽을 수

$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); 
temp.php 스크립트를 실행할 때


우리는 다음과 같은 출력을 얻을 :

$ php ./temp.php 
stdout : 
string(40) "this is on stdout 
this is on stdout too 
" 
stderr : 
string(40) "this is on stderr 
this is on stderr too 
" 


희망이 도움이 :-)

+3

이것을 사용할 때는 모두 깨끗하게하기 위해 proc_close를 사용해야합니다. –

+0

프로세스 var에 결과를 리디렉션하는 이유는 무엇입니까? –

+3

@BriceFavre 그는 프로세스 var에 넣기 때문에 나중에 프로세스가 종료 한 리턴 코드를 반환하는 proc_close를 사용하여 닫을 수 있습니다. Windows 환경에서'$ returnCode = proc_close ($ process);' –

6

병합 표준 출력/표준 오류를 얻을 수있는 또 다른 방법. 당신은 표준 출력을 무시하고 단지 표준 에러 얻고 싶은 경우에

$pp_name = "/tmp/pp_test"; 
@unlink($pp_name); 
posix_mkfifo($pp_name, 0777); 
$pp = fopen($pp_name, "r+"); 
stream_set_blocking($pp, FALSE); 
exec("wget -O - http://www.youtube.com 2>$pp_name", $r_stdout); 
$r_stderr = stream_get_contents($pp); 
var_dump($r_stderr); 
fclose($pp); 
unlink($pp_name); 

, 당신이 시도 할 수 있습니다 : 도움이 될 수

exec("wget -O - http://www.youtube.com 2>&1 >/dev/null", $r_stderr); 
30

약간의 기능 : 종료 코드가 반환

function my_shell_exec($cmd, &$stdout=null, &$stderr=null) { 
    $proc = proc_open($cmd,[ 
     1 => ['pipe','w'], 
     2 => ['pipe','w'], 
    ],$pipes); 
    $stdout = stream_get_contents($pipes[1]); 
    fclose($pipes[1]); 
    $stderr = stream_get_contents($pipes[2]); 
    fclose($pipes[2]); 
    return proc_close($proc); 
} 

을 필요한 경우 STDOUT 및 STDERR은 참조 매개 변수입니다.

+2

멋지고 단순하며 완벽하게 작동합니다. 게시 해 주셔서 감사합니다 !!! –