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

后端 未结 9 1877
南旧
南旧 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 22:40

    One line of code (line 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?.

    0 讨论(0)
  • 2020-12-23 22:54

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

    $handle = fopen("php://stdin", "r");
    $line = fgets($handle);
    if (trim($line) != 'yes') {
    ...
    
    0 讨论(0)
  • 2020-12-23 22:56

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

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

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

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

    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 while loop, and two function calls. PHP also has a readline interface for more advanced shell applications.

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

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

    <?php
     $line = trim(fgets(STDIN)); // reads one line from STDIN
     fscanf(STDIN, "%d\n", $number); // reads number from STDIN
    ?>
    
    0 讨论(0)
提交回复
热议问题