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

时间:2011-10-03 09:55:22

标签: php bash

我从PHP站点运行这个shell脚本。

在shell脚本(Audit shell脚本)中, 我有3个选择:

1)流程脚本 2)显示结果 3)退出

尝试下面的代码似乎不起作用,PHP网站显示空白。

<?php



session_start();


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

?>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

<?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>";

?>

在我看来,你可以正确阅读manual page for exec() ......

答案 1 :(得分:0)

尝试使用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 Manual's proc_open page

中提取此代码