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

后端 未结 9 1878
南旧
南旧 2020-12-23 21:59

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

相关标签:
9条回答
  • 2020-12-23 23:02

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

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

    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 {
      $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.

    0 讨论(0)
  • 2020-12-23 23:02

    My five cents: Using STDOUT and STDIN:

    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);
    
    0 讨论(0)
  • 2020-12-23 23:02

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

    0 讨论(0)
提交回复
热议问题