在 PHP 中,exec() 函式執行指令並從指令的 stdout 傳回輸出。但是,如果命令寫入 stderr,則 exec() 不會捕獲此輸出。
要從指令擷取 stdout 和 stderr,可以使用 proc_open() 函式。 proc_open() 提供對命令執行過程的更高層級的控制,包括透過管道傳輸命令的 stdin、stdout 和 stderr 流的能力。
範例:
範例:#!/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;
讓我們考慮以下 shell 腳本 test.sh,它同時寫入 stderr 和 stdout:
$descriptorspec = [ 0 => ['pipe', 'r'], // stdin 1 => ['pipe', 'w'], // stdout 2 => ['pipe', 'w'], // stderr ]; $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);
要在 PHP 中執行此腳本並捕獲 stdout 和 stderr,您可以使用以下程式碼:$descriptorspec = [ 0 => ['pipe', 'r'], // 標準輸入 1 => ['pipe', 'w'], // 標準輸出 2=> ['pipe', 'w'], // 標準錯誤 ]; $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]); 回顯“標準輸出:\n”; var_dump($stdout); 回顯「標準誤差:\n」; var_dump($stderr);
輸出:#!/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 腳本時,您將得到以下輸出:
stdout :
string(40)「這是在標準輸出上
這也在標準輸出上”
標準錯誤:
string(40) "這是在 stderr 上
這也在 stderr 上」
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3