【问题标题】:PHP, shell_exec and an inputPHP、shell_exec 和输入
【发布时间】:2012-07-29 01:13:08
【问题描述】:

shell_exec 是否可以执行给定的命令,其中初始命令会要求动态输入,然后是基于输入本身的命令。

我已经研究了几个小时来寻找答案,但我似乎找不到我要找的东西。

我有一个类似于下面示例的想法的要求,任何帮助将不胜感激,因为

$x = shell_exec("read -p 'Enter your name : ' x; echo 'Your name is' : $x");

回显 x 输出:

你的名字是

如您所见,我正在运行多个命令,但我不知道可以在输入字符串命令中的何处插入。

注意: 我试着做

$x = shell_exec("echo 'Foo' | read -p 'Enter your name : ' x; echo 'Your name is :' $x");

echo $x;

输出是:

你的名字是:

我期待

你的名字是:Foo

很明显,出了点问题。

【问题讨论】:

  • 你到底想运行什么shell命令?
  • 你需要在字符串$x = shell_exec("read -p 'Enter your name : ' x; echo 'Your name is' : \$x");中转义$x
  • 我尝试在 $x 之后添加 \,输出是“你的名字是:$x”
  • @Dagon 它很长,与织物脚本(python)和php有关,基本上,这个想法是在我运行该脚本之后,服务器会在初始shell命令后询问我用户密码,这必须从 php 运行,因为我将为命令提供动态数据(将变量连接到命令字符串)

标签: php input shell-exec


【解决方案1】:

我在其他时候也遇到过与read 相同的问题。如果在终端执行同一行,结果是一样的,所以这不是php问题,而是shell问题:

$ echo 'Foo' | read -p 'Enter your name : ' x; echo "Your name is : $x"
Your name is : 

如果您将read 包裹在while .. do .. done 中,那么一切都会完美运行:

$ echo 'Foo' | while read -p 'Enter your name : ' x; do echo "Your name is : $x" ; done
Your name is : Foo

我不知道为什么会这样。

您也可以尝试使用proc_open 和类似的,您将获得对输入/输出流的更多控制,但我不知道它们是否适用于read 问题。

【讨论】:

  • / mogria 你的综合建议给了我答案,经过反复试验, $x = shell_exec("echo 'foo' | while read -p 'enter your name : ' x; do echo '你的名字是:' \$x; done;");回声 $x;已经产生了我需要的东西。谢谢大家
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多