2013-01-03 227 views
2

我有一個特定的命令行程序,它接受來自流的輸入而不是命令行參數(例如,一個使用scanf輸入輸入的C程序)我如何與此交互應用程序使用PHP? exec(),shell_exec()不會在這裏幫助,因爲輸入不是通過命令行參數。我需要在PHP腳本和命令行程序之間建立一個連續的輸入/輸出連接,以便用戶可以給PHP一個輸入,哪個PHP將會中繼到程序中,然後獲取輸出,然後顯示給用戶。PHP與命令行程序的交互

回答

2

您可以使用proc_open。從該頁面

例子:

<?php 
$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", "/tmp/error-output.txt", "a") // stderr is a file to write to 
); 

$cwd = '/tmp'; 
$env = array('some_option' => 'aeiou'); 

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env); 

if (is_resource($process)) { 
    // $pipes now looks like this: 
    // 0 => writeable handle connected to child stdin 
    // 1 => readable handle connected to child stdout 
    // Any error output will be appended to /tmp/error-output.txt 

    fwrite($pipes[0], '<?php print_r($_ENV); ?>'); 
    fclose($pipes[0]); 

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

    // It is important that you close any pipes before calling 
    // proc_close in order to avoid a deadlock 
    $return_value = proc_close($process); 

    echo "command returned $return_value\n"; 
} 
?> 

輸出:

Array 
(
    [some_option] => aeiou 
    [PWD] => /tmp 
    [SHLVL] => 1 
    [_] => /usr/local/bin/php 
) 
command returned 0 
+0

謝謝。這有助於:) –