如何在PHP中从shell脚本中选择用户输入


How to select user input from a shell script in PHP?

我已经从一个PHP站点运行了这个shell脚本。

在shell脚本(审计shell脚本)中,我有3个选项:

1)处理脚本2)显示结果3)退出

尝试下面的代码,似乎不工作,PHP站点显示空白。

<?php

session_start();

exec('/Desktop/test.sh');
exec('1');
$output = exec('2');
echo "<pre>$output</pre>";
?>

<?php
  session_start();
  // This line executes '/Desktop/test.sh' as if it had been called from the
  // command line
  // exec('/Desktop/test.sh');
  // This line attempts to execute a file called '1', which would have to be
  // in the same directory as this script
  // exec('1');
  // This line attempts to execute a file called '2', which would have to be
  // in the same directory as this script, and capture the first line of the
  // output in $output
  // $output = exec('2');
  // I think you want to be doing something more like this - this executes the
  // shell script, passing "1" and "2" as arguments, and captures the whole
  // output as an array in $output
  exec('/Desktop/test.sh "1" "2"', $output);
  // Loop the output array and echo it to the browser
  echo "<pre>";
  foreach ($output as $lineno => $line) echo "Line $lineno: $line'n";
  echo "</pre>";
?>

在我看来,你可以正确阅读exec()的手册页…

尝试使用proc_open代替exec;它使您能够更好地控制过程输入/输出。比如:

<?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", "/dev/null", "a") // stderr is a file to write to
);
$cwd = '/Desktop';
$env = array();
$process = proc_open('/Desktop/test.sh', $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 sent to /dev/null (ie, discarded)
    fwrite($pipes[0], "1'n");
    fwrite($pipes[0], "2'n");
    fclose($pipes[0]);
    $output = 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 $output;
}
?>
注意:我从PHP手册的proc_open页面
中摘取了这段代码