PHP cli getting input from user and then dumping into variable possible?

后端 未结 3 531
野的像风
野的像风 2020-11-29 19:59

Is it possible to get input from a user using php cli and then dump the input into a variable and then the script goes ahead.

Just like the c++ cin func

相关标签:
3条回答
  • 2020-11-29 20:24

    You can simply do:

    $line = fgets(STDIN);
    

    to read a line from standard input in php CLI mode.

    0 讨论(0)
  • 2020-11-29 20:33

    Have a look at this PHP manual page http://php.net/manual/en/features.commandline.php

    in particular

    <?php
    echo "Are you sure you want to do this?  Type 'yes' to continue: ";
    $handle = fopen ("php://stdin","r");
    $line = fgets($handle);
    if(trim($line) != 'yes'){
        echo "ABORTING!\n";
        exit;
    }
    echo "\n";
    echo "Thank you, continuing...\n";
    ?>
    
    0 讨论(0)
  • 2020-11-29 20:36

    In this example I'm extending Devjar's example. Credits for him for example code. Last code example is simplest and safest in my opinion.

    When you use his code:

    <?php
    echo "Are you sure you want to do this?  Type 'yes' to continue: ";
    $handle = fopen ("php://stdin","r");
    $line = fgets($handle);
    if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
    }
    echo "\n";
    echo "Thank you, continuing...\n";
    ?>
    

    You should note stdin mode is not binary-safe. You should add "b" to your mode and use following code:

    <?php
    echo "Are you sure you want to do this?  Type 'yes' to continue: ";
    $handle = fopen ("php://stdin","rb"); // <-- Add "b" Here for Binary-Safe
    $line = fgets($handle);
    if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
    }
    echo "\n";
    echo "Thank you, continuing...\n";
    ?>
    

    Also you can set max charters. This is my personal example. I'll suggest to use this as your code. It's also recommended to use directly STDIN than "php://stdin".

    <?php
    /* Define STDIN in case if it is not already defined by PHP for some reason */
    if(!defined("STDIN")) {
    define("STDIN", fopen('php://stdin','rb'))
    }
    
    echo "Hello! What is your name (enter below):\n";
    $strName = fread(STDIN, 80); // Read up to 80 characters or a newline
    echo 'Hello ' , $strName , "\n";
    ?>
    
    0 讨论(0)
提交回复
热议问题