標籤:資訊 資源 null function
$cmd = "rm 1.txt";//刪除一個不存在的檔案,查看報錯資訊$res = doShell($cmd);var_dump($res);//該函數沒有限制條件,可以直接放在代碼中使用function doShell($cmd,$cwd=null){ $descriptorspec = array( 0 => array("pipe", "r"), // stdin 1 => array("pipe", "w"), // stdout 2 => array("pipe", "w") // stderr );// $cmd = ‘./test.sh‘; // 替換為你要執行的shell指令碼 /* * 傳回值 * 返回表示進程的資源類型, 當使用完畢之後,請調用 proc_close() 函數來關閉此資源。 如果失敗,返回 FALSE。 * cmd 要執行的命令 * descriptorspec 一個索引數組。 * 數組的鍵表示描述符, 0 表示標準輸入(stdin),1 表示標準輸出(stdout),2 表示標準錯誤(stderr) * 數組元素值表示 PHP 如何將這些描述符傳送至子進程。 * pipe (第二個元素可以是: r 向進程傳送該管道的讀取端,w 向進程傳送該管道的寫入端), * 以及 file(第二個元素為檔案名稱)。 * pipes * 將被置為索引數組, 其中的元素是被執行程式建立的管道對應到 PHP 這一端的檔案指標。 * cwd * 要執行命令的初始工作目錄。 必須是 絕對 路徑, 設定此參數為 NULL 表示使用預設值(當前 PHP 進程的工作目錄) * env * 要執行的命令所使用的環境變數。 設定此參數為 NULL 表示使用和當前 PHP 進程相同的環境變數。 * * */ $proc = proc_open($cmd, $descriptorspec, $pipes, $cwd, null); // $proc為false,表明命令執行失敗 if ($proc == false) { return false; // do sth with HTTP response } else { $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]); $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); $status = proc_close($proc); // 釋放proc } $data = array( ‘stdout‘ => $stdout, ‘stderr‘ => $stderr, ‘retval‘ => $status ); return $data;}
php 執行shell命令 列印錯誤資訊