如何编写命令行交互式 PHP 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2929629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:09:53  来源:igfitidea点击:

How do I write a command-line interactive PHP script?

phpshell

提问by user151841

I want to write a PHP script that I can use from the command line. I want it to prompt and accept input for a few items, and then spit out some results. I want to do this in PHP, because all my classes and libraries are in PHP, and I just want to make a simple command line interface to a few things.

我想编写一个可以从命令行使用的 PHP 脚本。我希望它提示并接受一些项目的输入,然后吐出一些结果。我想在 PHP 中执行此操作,因为我所有的类和库都在 PHP 中,我只想为一些事情制作一个简单的命令行界面。

The prompting and accepting repeated command line inputs is the part that's tripping me up. How do I do this?

提示和接受重复的命令行输入是让我失望的部分。我该怎么做呢?

采纳答案by aioobe

From PHP: Read from Keyboard – Get User Input from Keyboard Console by Typing:

PHP:从键盘读取 - 通过键入从键盘控制台获取用户输入

You need a special file: php://stdinwhich stands for the standard input.

您需要一个特殊文件:php://stdin它代表标准输入。

print "Type your message. Type '.' on a line by itself when you're done.\n";

$fp = fopen('php://stdin', 'r');
$last_line = false;
$message = '';
while (!$last_line) {
    $next_line = fgets($fp, 1024); // read the special file to get the user input from keyboard
    if (".\n" == $next_line) {
      $last_line = true;
    } else {
      $message .= $next_line;
    }
}

回答by Justin Ethier

The I/O Streamspage from the PHP manual describes how you can use STDIN to read a line from the command line:

PHP 手册中的I/O 流页面描述了如何使用 STDIN 从命令行读取一行:

<?php
 $line = trim(fgets(STDIN)); // reads one line from STDIN
 fscanf(STDIN, "%d\n", $number); // reads number from STDIN
?>

回答by Tim Post

I'm not sure how complex your input might be, but readlineis an excellent way to handle it for interactive CLI programs.

我不确定您的输入可能有多复杂,但readline是处理交互式 CLI 程序的绝佳方式。

You get the same creature comforts out of it that you would expect from your shell, such as command history.

您可以从中获得与 shell 相同的生物舒适度,例如命令历史记录。

Using it is as simple as:

使用它很简单:

$command = readline("Enter Command: ");
/* Then add the input to the command history */
readline_add_history($command);

If available, it really does make it simple.

如果可用,它确实使它变得简单。



Here a typical do-case-while for console implementation:

这是控制台实现的典型 do-case-while:

do {
  $cmd = trim(strtolower( readline("\n> Command: ") ));
  readline_add_history($cmd);
  switch ($cmd) {
    case 'hello': print "\n -- HELLO!\n"; break;
    case 'bye': break;
    default: print "\n -- You say '$cmd'... say 'bye' or 'hello'.\n";
  }
} while ($cmd!='bye');

where user can use arrows (up and down) to access the history.

用户可以使用箭头(向上和向下)访问历史记录。

回答by Serty Oan

I found an example on PHP.net, Utiliser PHP en ligne de commande:

我在 PHP.net 上找到了一个示例,Utiliser PHP en ligne de commande

$handle = fopen("php://stdin", "r");
$line = fgets($handle);
if (trim($line) != 'yes') {
...

回答by TerryP

The algorithm is simple:

算法很简单:

until done:
    display prompt
    line := read a command line of input
    handle line

It's very trivial to use an array that maps commands to callback functions that handle them. The entire challenge is roughly a whileloop, and two function calls. PHP also has a readline interfacefor more advanced shell applications.

使用将命令映射到处理它们的回调函数的数组非常简单。整个挑战大致是一个while循环和两个函数调用。PHP 还具有用于更高级 shell 应用程序的readline 接口

回答by John Erck

One line of code (line 2):

一行代码(第2行):

<?php
    $name = trim(shell_exec("read -p 'Enter your name: ' name\necho $name"));
    echo "Hello $name, this is PHP speaking\n";
    exit;

Checkout this answer's source in blog post How can I capture user input from the cmd line using PHP?.

在博客文章中查看此答案的来源如何使用 PHP 从 cmd 行捕获用户输入?.

回答by 2upmedia

Simple:

简单的:

#!/usr/bin/php
<?php
define('CONFIRMED_NO', 1);

while (1) {
    fputs(STDOUT, "\n"."***WARNING***: This action causes permanent data deletion.\nAre you sure you're not going to wine about it later? [y,n]: ");

    $response = strtolower(trim(fgets(STDIN)));
    if( $response == 'y' ) {
        break;
    } elseif( $response == 'n' ) {
        echo "\n",'So I guess you changed your mind eh?', "\n";
        exit (CONFIRMED_NO);
    } else {
        echo "\n", "Dude, that's not an option you idiot. Let's try this again.", "\n";
        continue;
    }
}

echo "\n","You're very brave. Let's continue with what we wanted to do.", "\n\n";

回答by dickwan

My five cents: Using STDOUTand STDIN:

我的五分钱:使用STDOUTSTDIN

fwrite(STDOUT, "Please enter your Message (enter 'quit' to leave):\n");

do{
    do{
        $message = trim(fgets(STDIN));
    } while($message == '');

    if(strcasecmp($message, 'quit') != 0){
        fwrite(STDOUT, "Your message: ".$message."\n");
    }

}while(strcasecmp($message,'quit') != 0);
// Exit correctly
exit(0);

回答by Joonas Trussmann

Basically you read from standard input. See Input/output streams.

基本上你从标准输入读取。请参阅输入/输出流