简体   繁体   English

在 PHP 中运行交互式 Shell 脚本

[英]Run an Interactive Shell Script in PHP

I have a shell script that requires input during runtime.我有一个需要在运行时输入的 shell 脚本。 Is it possible to echo input into the shell script during the exec()?是否可以在 exec() 期间将输入回显到 shell 脚本中?

IE in a normal shell: $ ./script.sh普通 shell 中的 IE:$ ./script.sh

Input: Whats your favorite color: [Type your answer] Red输入:你最喜欢什么颜色:[输入你的答案]红色

Output: Your favorite color is Red.输出:你最喜欢的颜色是红色。

I'm not sure exactly which side you are asking for, but I will answer both anyway.我不确定您到底要问哪一边,但无论如何我都会回答。

From PHP, you can read user input from the shell.在 PHP 中,您可以从 shell 读取用户输入。 It can be done using the readline() function or simply using streams.可以使用readline()函数或简单地使用流来完成。 Depending on the PHP version you are using and the environment, it can be either php://input or php://stdin.根据您使用的 PHP 版本和环境,它可以是 php://input 或 php://stdin。 You can simply fopen() on those and read as usual.你可以简单地 fopen() 在那些上并像往常一样阅读。

If you want to interact with a shell script you are calling, you will need to use proc_open() rather than exec.如果要与正在调用的 shell 脚本交互,则需要使用proc_open()而不是 exec。 It is a little more trouble, but there are no ways around.这有点麻烦,但没有办法。 The function will provide you with separate streams for input, output and error, you can read them as needed to do your task.该函数将为您提供单独的输入、输出和错误流,您可以根据需要读取它们以完成您的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM