2014-10-17 82 views
2

嗨我想在Windows機器上使用PHP執行多個命令。我試過這段代碼:PHP - 如何保持一個命令外殼打開執行多個命令?

<?php 
$output= shell_exec("powershell.exe"); 
$output2= shell_exec("write-host gokul"); 
shell_exec("exit"); 
echo('<pre>'); 
echo($output); 
echo($output2); 
echo('</pre>'); 
?> 

PHP用一個新shell執行每個命令並在完成時關閉它!

據我所知,每個'shell_exec'創建一個新的shell並且控件等待直到命令執行完成。我怎樣才能創建一個在後臺打開的shell直到我關閉呢?

我不確定'proc_open'或'popen'可以幫忙嗎?

UPDATE 當我嘗試PROC_OPEN()

$descriptorspec = array(
    0 => array("pipe", "r"), // stdin is a pipe that the child will read from 
    1 => array("pipe", "w"), // stdout is a pipe that the child will write to 
    2 => array("file", "error.txt", "a") // stderr is a file to write to 
);  
$process = proc_open('cmd.exe', $descriptorspec, $pipes); 

if (is_resource($process)) { 
    fwrite($pipes[0], 'dir'); 
    fwrite($pipes[0], 'powershell.exe'); 
    fwrite($pipes[0], 'write-host gokul'); 
    fclose($pipes[0]); 

    echo stream_get_contents($pipes[1]); 
    fclose($pipes[1]); 

    proc_close($process); 
} 

只會打印的提示。我真的可以使用proc_open來執行多個命令嗎?如果是這樣,怎麼樣?

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\wamp\bin\apache\Apache2.2.17>More? 
+1

是的,你可以使用'proc_open'。檢查它的手冊頁:http://php.net/manual/en/function.proc-open.php – hek2mgl 2014-10-17 10:01:59

+0

@ hek2mgl嗨,我試過proc_open。請查看問題編輯和幫助。 – 2014-10-20 11:01:41

+0

您是否嘗試過使用「&&」執行命令,請參閱:command1 && command2。我現在沒有任何Win-machine,但是這通常適用於* Nix機器 – 2014-10-20 11:08:43

回答

2

使用proc_open是正確的嘗試,但你需要完成一個新的行字符的每一個命令。就像你會在shell會話中手動輸入命令一樣。

它應該是這樣的:

fwrite($pipes[0], 'dir' . PHP_EOL); 
fwrite($pipes[0], 'powershell.exe' . PHP_EOL); 
fwrite($pipes[0], 'write-host gokul' . PHP_EOL);