php 執行shell命令 列印錯誤資訊

來源:互聯網
上載者:User

標籤:資訊   資源   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命令 列印錯誤資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.