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

后端 未结 9 1921
南旧
南旧 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.

提交回复
热议问题