對於在您不在乎中間檔案時捕獲 stdout 和 stderr,我使用 . . . 的效果更好
<?php
function cmd_exec($cmd, &$stdout, &$stderr)
{
$outfile = tempnam(".", "cmd");
$errfile = tempnam(".", "cmd");
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("file", $outfile, "w"),
2 => array("file", $errfile, "w")
);
$proc = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($proc)) return 255;
fclose($pipes[0]); $exit = proc_close($proc);
$stdout = file($outfile);
$stderr = file($errfile);
unlink($outfile);
unlink($errfile);
return $exit;
}
?>
這與重新導向沒什麼太大區別,只是它會為您處理暫存檔(您可能需要將目錄從「.」變更),並且由於 proc_close 呼叫,它會自動封鎖。這模擬了 shell_exec 的行為,並讓您取得 stderr。